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"); } }
/*Cria os objetos Licitacao, Lote e LicitacaoArquivo*/ private static void HandleCreate(HtmlDocument htmlDocument) { try { string linkEdital = Constants.CMG_SITE + Constants.CMG_LINK_EDITAL + htmlDocument.DocumentNode.Descendants("a").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("arquivoDoEdital")).Attributes["href"].Value; /*Verifica se o pregão já não esta na base de dados*/ if (!string.IsNullOrEmpty(Id) && !LicitacaoController.Exists(Id)) { Licitacao licitacao = CreateLicitacao(htmlDocument, linkEdital); if (licitacao != null) { Repo.Insert(licitacao); RService.Log("(HandleCreate) " + Name + ": Licitação " + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); CreateLicitacaoArquivo(licitacao, linkEdital); //SegmentarLicitacao(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(Id) && LicitacaoController.Exists(Id) && LicitacaoController.SituacaoAlterada(Id, Situacao)) { Licitacao licitacao = LicitacaoController.GetByIdLicitacaoFonte(Id); licitacao.Situacao = Situacao; LicitacaoRepository 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"); } }
/*Metodo que inicia o processamento de dados*/ private static void Init() { RService.Log("(Init) " + Name + ": Começando o processamento... " + "at {0}", Path.GetTempPath() + Name + ".txt"); try { Repo = new LicitacaoRepository(); /*Realiza a atualização das situações das licitações já inseridas*/ //UpdateLicitacoes(); /*Inicia listas e dictionary's com informações necessárias*/ NameToOrgao = OrgaoController.GetNomeUfToOrgao(); NameToModalidade = ModalidadeController.GetNameToModalidade(); UfToCapital = CityUtil.GetUfToCapital(); UfToNomeCidadeToIdCidade = CidadeController.GetUfToNameCidadeToIdCidade(); Lote = LoteController.CreateLote(43, IdFonte); TryReload = true; if (DoSearch()) { /*Percorre cada licitação encontrada*/ foreach (var numUf in numUFs) { /*Acessa a página da licitação*/ try { if (!LicitacaoController.Exists(numUf.Split(':')[0])) { /*Cria o objeto licitação com as informações da página*/ Licitacao licitacao = CreateLicitacao(numUf); if (licitacao != null) { Repo.Insert(licitacao); NumLicitacoes++; RService.Log("(Init) " + Name + ": Licitação inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); /*Segmenta a licitação recém criada*/ //SegmentarLicitacao(licitacao); DownloadEdAndCreatLicArq(licitacao); } else { if (licitacao != null && licitacao.Orgao != null) { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " e órgão " + licitacao.Orgao.Nome + " - " + licitacao.Orgao.Estado + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } else { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + numUf.Split(':')[0] + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } } } catch (Exception e) { RService.Log("Exception (Init - CreateLicitacao) " + 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"); } }
/*Cria uma nova licitacao e o lote se for necessário*/ public static bool CreateLicitacao() { try { string entidadeExecutora = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnmExecutor")).GetAttribute("value"); string objeto = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdsObjeto")).GetAttribute("value"); string numLicitacao = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrProcessoEdital")).GetAttribute("value"); string preco = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbvlReferencia")).GetAttribute("value"); string dotacao = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrDotacaoOrcamentaria")).GetAttribute("value"); string modalidade = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdsModalidadeLicitacao")).GetAttribute("value"); string numProcesso = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrEditalOrigem")).GetAttribute("value"); string dataLancamento = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtLancamentoPublicacao")).GetAttribute("value"); string precoMax = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbvlReferencia")).GetAttribute("value"); string dataAberturaEntrega = ""; if (CidadeAtual == "Diamante do Oeste") { CidadeAtual = "Diamante d'Oeste"; } if (Regex.IsMatch(web.PageSource, @"ctl00_ContentPlaceHolder1_tbdtAberturaLicitacao", RegexOptions.IgnoreCase)) { dataAberturaEntrega = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtAberturaLicitacao")).GetAttribute("value"); //Caso a licitação tenha o campo NOVA Data Abertura preenchido if (Regex.IsMatch(web.PageSource, @"ctl00_ContentPlaceHolder1_tbdtAberturaNova", RegexOptions.IgnoreCase)) { string dataNovaAberturaEntrega = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtAberturaNova")).GetAttribute("value"); if (!string.IsNullOrEmpty(dataNovaAberturaEntrega)) { dataAberturaEntrega = dataNovaAberturaEntrega; } } string cod = GenerateCod(entidadeExecutora, dataLancamento, numProcesso, preco); string scod = cod.ToString().Substring(0, 19); long numLong = 0; long numScod = long.TryParse(scod, out numLong) ? numLong : 0; if (!string.IsNullOrEmpty(scod) && !LicitacaoController.Exists(scod)) { if (!LicitacaoController.Exists(objeto, preco, "Dotação Orçamentária: " + dotacao, numLicitacao, numProcesso, Constants.TCEPR_HOST)) { RService.Log("(CreateLicitacao) " + Name + ": Criando licitação num... " + scod + " at {0}", Path.GetTempPath() + Name + ".txt"); Licitacao licitacao = new Licitacao(); licitacao.Objeto = objeto; licitacao.Processo = numProcesso; licitacao.IdLicitacaoFonte = numScod; licitacao.IdFonte = 510; licitacao.Excluido = 0; licitacao.SegmentoAguardandoEdital = 0; licitacao.DigitacaoUsuario = 43; //Robo licitacao.Lote = Lote; //licitacao.DigitacaoData = null; //licitacao.ProcessamentoData = null; licitacao.Observacoes = "Dotação Orçamentária: " + dotacao + " / Data de lançamento do edital pela entidade executora: " + dataLancamento; licitacao.LinkSite = Constants.TCEPR_HOST; licitacao.Cidade = CidadeAtual; licitacao.CidadeFonte = CidadeController.GetIdCidade(CidadeAtual, Constants.TCEPR_UF); licitacao.EstadoFonte = Constants.TCEPR_UF; licitacao.Estado = Constants.TCEPR_ESTADO; licitacao.Modalidade = NameToModalidade.ContainsKey(StringHandle.RemoveAccent(modalidade).ToUpper()) ? NameToModalidade[StringHandle.RemoveAccent(modalidade).ToUpper()] : null; licitacao.Num = numLicitacao; licitacao.AberturaData = DateHandle.Parse(dataAberturaEntrega, "dd/MM/yyyy"); licitacao.EntregaData = DateHandle.Parse(dataAberturaEntrega, "dd/MM/yyyy"); licitacao.ValorMax = precoMax; licitacao.Orgao = OrgaoController.GetOrgaoByNameAndUf(entidadeExecutora.Trim() + ":PR", NameToOrgao); if (LicitacaoController.IsValid(licitacao, out mensagemErro)) { Repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("Licitacao salva com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); TotalLic++; } else { if (licitacao.Orgao != null) { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " e órgão " + licitacao.Orgao.Nome + " - " + licitacao.Orgao.Estado + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } else { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } } } } } catch (Exception e) { RService.Log("Exception (CreateLicitacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } return(true); }
private static void HandleLicitacoes(int index) { RService.Log("(HandleLicitacoes) " + name + ": Consultando licitações da " + Constants.TCESE_MUN_NAME[index] + " at {0}", logPath); //LoadWebDriver(); LoadDriver(); try { string urlMunicipio = string.Format(Constants.TCESE_MUN_PAGE, Constants.TCESE_MUN_CODE[index], Constants.TCESE_MUN_NAME[index].Replace(" ", "%20")); temLicitacao = false; web.Navigate().GoToUrl(urlMunicipio); var licits = web.FindElements(By.TagName("a")).Where(x => x.GetAttribute("innerText").Contains("Ano/Número:")); repo = new LicitacaoRepository(); foreach (var licit in licits) { var dates = StringHandle.GetMatches(licit.Text, @"\d+/\d+/\d+"); if (Convert.ToDateTime(dates[0].Value) > DateTime.Today) { temLicitacao = true; var licitLink = licit.GetAttribute("href"); Licitacao licitacao = CreateLicitacao(licitLink, index); if (licitacao != null) { if (!LicitacaoController.Exists(licitacao.IdLicitacaoFonte.ToString())) { repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("(HandleLicitacoes) " + name + ": Licitação Nº" + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", logPath); numLicitacoes++; } } else { RService.Log("Exception (CreateLicitacao) " + name + ": Licitação não salva. Motivo: " + mensagemErro + " at {0}", logPath); } } } if (!temLicitacao) { RService.Log("(HandleLicitacoes) " + name + ": " + Constants.TCESE_MUN_NAME[index] + " não possui licitações novas at {0}", logPath); } } catch (Exception e) { RService.Log("Exception (HandleLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", logPath); } finally { if (web != null) { web.Close(); } } }
//Método para pegar as licitações do site do TCE-PI private static void GetLicitacoes() { try { //var webdriver = WebDriverChrome.LoadWebDriver(name); //var webdriver = WebDriverPhantomJS.LoadWebDriver(name, web); //web = webdriver.Item1; //wait = webdriver.Item2; if (web != null) { web.Quit(); } var driver = ChromeDriverService.CreateDefaultService(); driver.HideCommandPromptWindow = true; var op = new ChromeOptions(); op.AddUserProfilePreference("download.default_directory", TCEPIController.pathEditais); web = new ChromeDriver(driver, op, TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(Constants.TCEPI_SITE); wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]"))); web.FindElement(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]")).Click(); Thread.Sleep(3000); /*Laço que se repete até o fim das licitações. O fim é demarcado pela quantidade de licitações na lista licitNums: * em cada página o número é 50, menos na última página. Quando o número for diferente de 50, ele termina*/ do { licitNums = new List <string>(); RService.Log("(GetLicitacoes) " + name + ": Acessando página " + currentPage + " at {0}", logPath); string pageHtml = web.PageSource.ToString(); var licits = StringHandle.GetMatches(pageHtml, @"\?id=\d{6}"); //Pega os números das licitações da página em questão foreach (var licit in licits) { string licNum = licit.ToString().Replace("?id=", ""); licitNums.Add(licNum); } RService.Log("(GetLicitacoes) " + name + ": Acessando licitações da página " + currentPage + " at {0}", logPath); foreach (string lic in licitNums) { if (!alreadyInserted.Contains(Int64.Parse(lic))) { Licitacao licitacao = CreateLicitacao(lic); if (licitacao != null && !LicitacaoController.Exists(licitacao.IdLicitacaoFonte.ToString())) { repo = new LicitacaoRepository(); try { repo.Insert(licitacao); RService.Log("(GetLicitacoes) " + name + ": Licitação " + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", logPath); numLicitacoes++; GetFiles(licitacao); } catch (Exception e) { RService.Log("Exception (GetLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / Mensagem de erro: " + mensagemErro + " at {0}", logPath); } } } } //webdriver = WebDriverChrome.LoadWebDriver(name); //web = webdriver.Item1; //wait = webdriver.Item2; web = new ChromeDriver(driver, op, TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(Constants.TCEPI_SITE); web.FindElement(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]")).Click(); for (int i = 0; i < currentPage; i++) { wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id=\"formListaLic:listaLic_paginator_top\"]/a[3]"))); web.FindElement(By.XPath("//*[@id=\"formListaLic:listaLic_paginator_top\"]/a[3]")).Click(); Thread.Sleep(10000); } currentPage++; } while (licitNums.Count() == 10); } catch (Exception e) { StackTrace st = new StackTrace(e, true); var frame = st.GetFrame(st.FrameCount - 1); var line = frame.GetFileLineNumber(); RService.Log("Exception (GetLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at line " + line + " at {0}", logPath); } }