private static void InitializeUtils() { Orgaos = OrgaoRepository.FindByUF(Constants.CRJ_ESTADO_FONTE); NameToModalidade = ModalidadeController.GetNameToModalidade(); Cidades = CidadeController.GetNameToCidade(Constants.CRJ_ESTADO_FONTE); repo = new LicitacaoRepository(); Lote = LoteController.CreateLote(43, Constants.CRJ_ID_FONTE); //AlreadyInserted = LicitacaoController.GetAlreadyInserted(Constants.CRJ_HOST); }
/*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); } } }
/*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")); //Criar um novo lote se for preciso, verifica o status da oc e também se já esta salva no bd if (!string.IsNullOrEmpty(ocn) && !LicitacaoController.ExistsBEC(ocn)) { //Preenche os dados da licitação e retorna para inserir na lista Licitacao licitacao = CreateLicitacao(htmlDoc, ocnum, situacao); if (licitacao != null && LicitacaoController.IsValid(licitacao, out mensagemErro)) { licitacao.Observacoes = ocn; licitacao.LinkEdital = href.Replace("OC_Item", "Edital"); Repo = new LicitacaoRepository(); Repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("(HandleCreate) " + Name + ": inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); CreateLicitacaoArquivo(licitacao, licitacao.LinkEdital); 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"); } }
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"); } }
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"); } }
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"); } }
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); } }
//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); } }
internal static List <Licitacao> FindByRangeHistoric(string site, DateTime dataLimite) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.FindByRangeHistoric(site, dataLimite)); }
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(); } } }
internal static void UpdateSituacaoByIdLicitacao(int id, string situacao) { LicitacaoRepository repo = new LicitacaoRepository(); repo.UpdateSituacaoByIdLicitacao(id, situacao); }
internal static List <Licitacao> GetAberturaGratherThan(DateTime now, string site) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.FindBySiteAndAberturaGratherThan(now, site)); }
/*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"); } }
internal static Licitacao GetByIdLicitacaoFonte(string idLicitacaoFonte) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.GetByIdLicitacaoFonte(idLicitacaoFonte)); }
internal static bool SituacaoAlteradaBEC(string observacoes, string situacao) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.SituacaoAlteradaBEC(observacoes, situacao)); }
internal static Licitacao GetByObservacoes(string observacoes) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.GetByObservacoes(observacoes)); }
internal static bool SituacaoAlterada(string idLicitacaoFonte, string situacao) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.SituacaoAlterada(idLicitacaoFonte, situacao)); }
internal static bool ExistsBEC(string observacoes) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.ExistsBEC(observacoes)); }
internal static bool ExistsCNET(long idFonte) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.ExistsCNET(idFonte)); }
internal static bool ExistsCNET(string uasg, string pregao, int modalidade) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.ExistsCNET(uasg, pregao, modalidade)); }
internal static bool Exists(string idLicitacaoFonte) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.Exists(idLicitacaoFonte)); }
/*Inicia a busca*/ private static void Init() { RService.Log("(Init) " + Name + ": Começando o processamento.." + " at {0}", Path.GetTempPath() + Name + ".txt"); try { /*Inicia navegador fantasma*/ LoadDriver(); /*Acessa o site do TCE*/ web.Navigate().GoToUrl(Constants.TCEPR_SITE); /*Busca os itens do filtro por cidades*/ GetCidades(); /*Configura os parametros da busca e inicia demais componentes necessários*/ if (config.PreTypedDate != null) { CurrentDay = config.PreTypedDate.Value.AddDays(-2); FinalDay = config.PreTypedDate.Value; config.PreTypedDate = null; ConfigRobotController.Update(config); } else { CurrentDay = DateTime.Now.AddDays(-2); FinalDay = DateTime.Now; } NameToModalidade = ModalidadeController.GetNameToModalidade(); NameToOrgao = OrgaoController.GetNomeUfToOrgao(); Lote = LoteController.CreateLote(43, 510); Repo = new LicitacaoRepository(); CurrentPg = 1; TotalLic = 0; /*Procura licitacoes por cidade pra ointervalo de dias indicado*/ foreach (var cidade in dicCidades) { CidadeAtualKey = cidade.Key; CidadeAtual = cidade.Value; /*Pesquisa licitações com base nos parametros (ano; dtAbertura)*/ if (DoSearch(CurrentDay, FinalDay)) { /*Pra cada pag que a pesquisa retornar*/ do { /*Percorre licitações de uma pag*/ if (!GetLicitacoes()) { //Segunda e ultima tentativa, se não conseguir continua com a pesquisa para a proxima cidade DoSearch(CurrentDay, FinalDay); GetLicitacoes(); } } while (HasNextPage()); } Tens = new List <int>() { 11 }; CurrentPg = 1; } //Repo.Insert(licitacoes); } catch (Exception e) { RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } finally { if (TotalLic <= 0) { LoteController.Delete(Lote); } if (web != null) { web.Close(); } } }
internal static bool ExistsTCERS(long idLicitacaoFonte, int idFonte) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.ExistsTCERS(idLicitacaoFonte, idFonte)); }
/*Busca a licitação item por item*/ internal static bool Exists(string objeto, string valorMax, string observacaoes, string num, string processo, string linkSite) { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.Exists(objeto, valorMax, observacaoes, num, processo, linkSite)); }
private static void Init() { RService.Log("(Init) " + Name + ": Iniciando busca... at {0}", LogPath); try { repo = new LicitacaoRepository(); Orgaos = OrgaoRepository.FindByUF(Constants.TCERS_ESTADO_FONTE); NameToModalidade = ModalidadeController.GetNameToModalidade(); Cidades = CidadeController.GetNameToCidade(Constants.TCERS_ESTADO_FONTE); Lote = LoteController.CreateLote(43, Constants.TCERS_ID_FONTE); if (web != null) { web.Quit(); } var driver = ChromeDriverService.CreateDefaultService(); driver.HideCommandPromptWindow = true; var op = new ChromeOptions(); op.AddUserProfilePreference("download.default_directory", PathEditais); web = new ChromeDriver(driver, new ChromeOptions(), TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(Constants.TCERS_HOST); web.FindElement(By.XPath("//*[@id=\"t_TreeNav_1\"]/div[2]/a")).Click(); web.FindElement(By.XPath("//*[@id=\"R4830475339138649_actions_button\"]")).Click(); web.FindElement(By.XPath("//*[@id=\"R4830475339138649_actions_menu_3i\"]")).Click(); try { Actions actions = new Actions(web); actions.MoveToElement(web.FindElement(By.XPath("//*[@id=\"R4830475339138649_actions_menu_3i\"]"))).Perform(); actions.MoveToElement(web.FindElement(By.XPath("//*[@id=\"R4830475339138649_actions_menu_3_0_c9\"]"))).Perform(); web.FindElement(By.XPath("//*[@id=\"R4830475339138649_actions_menu_3_0_c9\"]")).Click(); } catch (Exception e) { RService.Log("(Exception) " + Name + ": Elemento 3 at {0}", LogPath); } Thread.Sleep(10000); var html = web.PageSource; var licits = new List <string>(); Regex licitRx = new Regex("f\\?p=(.*?)\">"); if (licitRx.IsMatch(html)) { var matches = licitRx.Matches(html); foreach (var mt in matches) { if (mt.ToString().Contains("ID_LICITACAO")) { var treatedLink = mt.ToString().Replace("\">", "").Replace("amp;", ""); licits.Add(Constants.TCERS_BASEURL + treatedLink); } } } GetLicitacoes(licits); } catch (Exception e) { RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath); } }
internal static List <Licitacao> FindBySituationBB() { LicitacaoRepository repo = new LicitacaoRepository(); return(repo.FindBySituationBB()); }
/*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); } } }