Пример #1
0
        private RServiceMiddleware BuildMiddleware(TestSink sink, string routePath = null, Delegate.Activator routeActivator  = null,
                                                   RequestDelegate handler         = null, IOptions <RServiceOptions> options = null, IServiceProvider serviceProvider = null,
                                                   IService service = null)
        {
            options = options ?? _options;

            var loggerFactory = new TestLoggerFactory(sink, true);
            var next          = handler ?? (c => Task.FromResult <object>(null));
            var rservice      = new RService(options);

            if (serviceProvider == null)
            {
                var mockServiceProvider = new Mock <IServiceProvider>().SetupAllProperties();
                mockServiceProvider.Setup(x => x.Invoke(It.IsAny <HttpContext>()))
                .Returns(Task.FromResult(0));

                serviceProvider = mockServiceProvider.Object;
            }

            if (!routePath.IsNullOrEmpty() && routeActivator != null)
            {
                rservice.Routes.Add(routePath, new ServiceDef
                {
                    ServiceMethod = routeActivator,
                    ServiceType   = service?.GetType() ?? typeof(IService)
                });
            }

            return(new RServiceMiddleware(next, loggerFactory, rservice, serviceProvider, options));
        }
Пример #2
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");
     }
 }
Пример #3
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);
            }
        }
        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");
            }
        }
Пример #5
0
        private static void GetCaptchaImg(IWebElement webElement, Bitmap image, string tempImgCrop)
        {
            RService.Log("(GetCaptchaImg) " + Name + ": Achando captcha... " + "at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                Point p = webElement.Location;

                int eleWidth  = webElement.Size.Width;
                int eleHeight = webElement.Size.Height;

                Size      size = new Size(eleWidth, eleHeight);
                Rectangle r    = new Rectangle(p, size);

                Image ib = image.Clone(r, image.PixelFormat);

                ib.Save(tempImgCrop);

                if (image != null)
                {
                    image.Dispose();
                }

                if (ib != null)
                {
                    ib.Dispose();
                }
            }
            catch (Exception ex)
            {
                RService.Log("Exception (GetCaptchaImg) " + Name + ": " + ex.Message + " / " + ex.StackTrace + " / " + ex.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
Пример #6
0
 public HomeController(NewsService newsService, UserService userService, FileService fileService, RService RService)
 {
     _newsService = newsService;
     _userService = userService;
     _fileService = fileService;
     _RService    = RService;
 }
Пример #7
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);
        }
Пример #8
0
        private static Preco CreatePreco(HtmlNode itemInfo, HtmlNode itemEvents, int id)
        {
            Preco preco = new Preco();

            var infoNodes = itemInfo.ChildNodes[1].ChildNodes[3];
            var priceNode = itemInfo.ChildNodes[1].ChildNodes[5];
            var dateNode  = itemEvents.ChildNodes[1].ChildNodes[3].ChildNodes[9];

            try
            {
                preco.IdLicitacao     = id;
                preco.Item            = GetNomeItem(infoNodes.ChildNodes[3]);
                preco.Descricao       = GetDescricaoItem(infoNodes.ChildNodes[3]);
                preco.Quantidade      = GetQuantidadeItem(infoNodes.ChildNodes[3]);
                preco.ValorEstimado   = GetValorEstimadoItem(infoNodes.ChildNodes[3]);
                preco.ValorHomologado = GetValorHomologado(priceNode);
                preco.DataHomologacao = GetDataHomologacao(dateNode);
                preco.DataInsercao    = DateTime.Now;
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreatePreco) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }

            return(preco);
        }
Пример #9
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);
            }
        }
Пример #10
0
        private static void GetPrecos(HtmlNode grupo, Licitacao licitacao)
        {
            try
            {
                var itens = grupo.ChildNodes.Where(i => i.InnerText.Contains("Item")).ToList();

                for (int i = 0; i < itens.Count; i += 2)
                {
                    int j = i + 1;

                    if (itens[i].InnerText.Contains("Homologado"))
                    {
                        Preco preco = CreatePreco(itens[i], itens[j], licitacao.Id);

                        if (preco != null && !repo.Exists(preco))
                        {
                            repo.Insert(preco);
                            NumPrecos++;
                            RService.Log("(GetPrecos) " + Name + ": Preço obtido com sucesso para licitacao " + licitacao.Id + " at {0}", LogPath);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetPrecos) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
Пример #11
0
        /*Retorna o Html de uma página*/
        internal static HtmlDocument GetHtmlDocOfPage(string uri, NameValueCollection formparameters = null, string metodo = "POST")
        {
            HtmlDocument htmlDoc = new HtmlDocument();

            if (formparameters == null)
            {
                formparameters = new NameValueCollection();
            }
            try
            {
                using (CookieAwareWebClient wc = new CookieAwareWebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    wc.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)";
                    htmlDoc.LoadHtml(HttpUtility.HtmlDecode(Encoding.UTF8.GetString(wc.UploadValues(uri, metodo, formparameters))));
                }
            }
            catch (Exception e)
            {
                string parameters = string.Empty;
                foreach (string param in formparameters.Keys)
                {
                    parameters += formparameters[param].ToString() + ";";
                }
                RService.Log("RService Exception WebHandle: (GetHtmlDocOfPage) " + uri + " " + parameters + " " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                return(null);
            }
            return(htmlDoc);
        }
Пример #12
0
        /*Retorna o Html de uma página*/
        internal static HtmlDocument HtmlParaObjeto(string link, Encoding e)
        {
            HtmlDocument htmlDoc = new HtmlDocument();

            try
            {
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(link);
                wr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
                using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                        using (MemoryStream ms = new MemoryStream())
                        {
                            stream.CopyTo(ms);
                            htmlDoc.LoadHtml(HttpUtility.HtmlDecode(e.GetString(ms.ToArray())));
                        }

                if (string.IsNullOrEmpty(htmlDoc.DocumentNode.InnerHtml))
                {
                    RService.Log("Exception WebHandle: (HtmlParaObjeto) Não foi possivel tranformar o HTML at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                }
            }
            catch (Exception ex)
            {
                RService.Log("Exception WebHandle: (HtmlParaObjeto)" + ex.Message + " / " + ex.StackTrace + " / " + ex.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
            }
            return(htmlDoc);
        }
Пример #13
0
        internal static bool DownloadFileWebRequest(ReadOnlyCollection <OpenQA.Selenium.Cookie> AllCookies, string url, string path)
        {
            try
            {
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
                wr.CookieContainer = new CookieContainer();
                foreach (var c in AllCookies)
                {
                    System.Net.Cookie cookie = new System.Net.Cookie(c.Name, c.Value, c.Path, c.Domain);
                    wr.CookieContainer.Add(cookie);
                }
                wr.UserAgent         = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
                wr.AllowAutoRedirect = true;

                using (HttpWebResponse myHttpWebResponse = wr.GetResponse() as HttpWebResponse)
                    using (Stream remote = myHttpWebResponse.GetResponseStream())
                        using (Stream local = File.Create(path))
                        {
                            byte[] buffer = new byte[1024];
                            int    bytesRead;

                            do
                            {
                                bytesRead = remote.Read(buffer, 0, buffer.Length);
                                local.Write(buffer, 0, bytesRead);
                            } while (bytesRead > 0);
                        }
                return(true);
            }
            catch (Exception e)
            {
                RService.Log("RService Exception WebHandle: (DownloadFileWebRequest) [LinkFile : " + url + "] " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                return(false);
            }
        }
Пример #14
0
        /*Busca arquivos de edital para licitações antigas que tenham data de abertura maior do que o dia corrente.*/
        private static void RemainingFiles()
        {
            RService.Log("(RemainingFiles) " + Name + ": Buscando arquivos de licitações antigas..." + " at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                /*Busca licitações com a data de abertura maior do que o dia corrente*/
                List <Licitacao> licitacoes = LicitacaoController.GetAberturaGratherThan(DateTime.Today, Constants.BB_HOST);

                TryReload = true;

                foreach (Licitacao lic in licitacoes)
                {
                    //if (lic.DigitacaoData.HasValue)
                    //{
                    /*Verifica e baixa os arquivos que ainda não foram coletados*/
                    DownloadEdAndCreatLicArq(lic.IdLicitacaoFonte.ToString(), lic);
                    //}
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (RemainingFiles) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
            finally
            {
                if (web != null)
                {
                    web.Close();
                }
            }
        }
Пример #15
0
        private static void Init()
        {
            try
            {
                //var loadedDriver = WebDriverChrome.LoadWebDriver(Name);
                //web = loadedDriver.Item1;
                //wait = loadedDriver.Item2;
                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));

                RService.Log("(Init) " + Name + ": Acessando a homepage... at {0}", LogPath);

                InitializeUtils();

                Navigate();
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
Пример #16
0
        /*Envia um arquivo por ftp*/
        internal static bool SendFileFtp(FTP ftpHandle, string nomeRobo)
        {
            bool segundaTentativa = false;

            do
            {
                try
                {
                    if (File.Exists(ftpHandle.FilePath + ftpHandle.FileName))
                    {
                        RService.Log("FTP: Iniciando envio at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                        Uri           uri = new Uri(ftpHandle.Adress + ftpHandle.FileName);
                        FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uri);
                        ftp.Credentials = new NetworkCredential(ftpHandle.UserName, ftpHandle.Password);
                        ftp.KeepAlive   = false;
                        ftp.Method      = WebRequestMethods.Ftp.UploadFile;
                        ftp.UseBinary   = true;

                        RService.Log("FTP: Abrindo stream arquivo local at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");

                        using (FileStream fStream = File.OpenRead(ftpHandle.FilePath + ftpHandle.FileName))
                        {
                            RService.Log("FTP: Arquivo [FileName: " + ftpHandle.FilePath + ftpHandle.FileName + "] at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                            byte[] buffer = new byte[fStream.Length];
                            ftp.ContentLength = buffer.Length;

                            using (Stream stream = ftp.GetRequestStream())
                            {
                                RService.Log("RService FTP: Enviando... at {0}", Path.GetTempPath() + nomeRobo + ".txt");
                                fStream.CopyTo(stream);
                            }
                        }
                        RService.Log("RService FTP Finished at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                        return(true);
                    }
                    else
                    {
                        RService.Log("RService Exception FTP: (SendFileFtp) Arquivo " + ftpHandle.FilePath + ftpHandle.FileName + " para o envio não existe at {0}", Path.GetTempPath() + nomeRobo + ".txt");
                    }
                }
                catch (Exception e)
                {
                    RService.Log("RService Exception FTP: (SendFileFtp: " + ftpHandle.FilePath + ftpHandle.FileName + ")" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    /*Faz uma segunda tentativa de envio*/
                    segundaTentativa = !segundaTentativa;
                    if (segundaTentativa)
                    {
                        RService.Log("FTP: Segunda tentativa de envio... at {0}", Path.GetTempPath() + nomeRobo + ".txt");
                        Thread.Sleep(5000);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }while (segundaTentativa);

            return(false);
        }
Пример #17
0
        /*Busca arquivos de edital para licitações antigas que tenham data de abertura maior do que o dia corrente.*/
        private static void HistoricFiles()
        {
            RService.Log("(HistoricFiles) " + Historic + ": Buscando licitações..." + " at {0}", Path.GetTempPath() + Historic + ".txt");
            try
            {
                DateTime dataLimite = DateTime.Today.AddDays(-90);

                /*Busca licitações com a data de abertura anterior a 90 dias, ou que ainda não aconteceu*/
                List <Licitacao> licitacoes = LicitacaoController.FindByRangeHistoric(Constants.CN_HOST, dataLimite);

                RService.Log("(HistoricFiles) " + Historic + ": " + licitacoes.Count + " licitacões encontradas at {0}", Path.GetTempPath() + Historic + ".txt");

                licitacoesHistorico = new List <string>();

                foreach (Licitacao licitacao in licitacoes)
                {
                    RService.Log("(HistoricFiles) " + Historic + ": Consultando ata e histórico da licitação " + licitacao.IdLicitacaoFonte + " at {0}", Path.GetTempPath() + Historic + ".txt");
                    ConsultaAtaPregao(licitacao);
                    GetHistoricos(licitacao, Historic);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HistoricFiles) " + Historic + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
            }
        }
Пример #18
0
        /*Recorta imagem do captcha da img da pag para enviar pro decodificador*/
        private static void GetCaptchaImg(IWebElement element, Bitmap screenShot, string cutCaptchaFile)
        {
            RService.Log("(GetCaptchaImg) " + GetNameRobot() + ": Achando captcha... " + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");
            try
            {
                Point p = element.Location;

                int eleWidth  = element.Size.Width;
                int eleHeight = element.Size.Height;

                Size      size = new Size(eleWidth, eleHeight);
                Rectangle r    = new Rectangle(p, size);

                Image ib = screenShot.Clone(r, screenShot.PixelFormat);

                ib.Save(cutCaptchaFile);

                screenShot.Dispose();
                ib.Dispose();
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetCaptchaImg) " + GetNameRobot() + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");
            }
        }
Пример #19
0
        //Preenche o formulario para fazer o download e recupera os cookies
        private static void FillForm(string parametros)
        {
            try
            {
                string url = string.Format("http://www.licitacoes-e.com.br/aop/lct/licitacao/consulta/CadastrarInteressedital.jsp?{0}", parametros);
                web.Navigate().GoToUrl(url);

                web.ExecuteScript(string.Format("document.getElementById('nomeEmpresa').value = '{0}'", "Otavio"));
                web.ExecuteScript(string.Format("document.getElementById('endereco').value = '{0}'", "Rua das Aguias"));
                web.ExecuteScript(string.Format("document.getElementById('bairro').value = '{0}'", "Curitiba"));
                web.ExecuteScript(string.Format("document.getElementById('cidade').value = '{0}'", "Diadema"));
                web.ExecuteScript(string.Format("document.getElementById('cep').value = '{0}'", "81000-000"));
                web.ExecuteScript(string.Format("document.getElementById('uf').value = '{0}'", "AM"));
                web.ExecuteScript(string.Format("document.getElementById('codigoTipoDocumentoCnpj').checked = '{0}'", "true"));
                web.ExecuteScript(string.Format("document.getElementById('textoDocumentoPessoaJuridica').value = '{0}'", "46824418000114"));

                web.ExecuteScript(string.Format("document.getElementById('contato').value = '{0}'", "Keller Ches"));
                web.ExecuteScript(string.Format("document.getElementById('ddd').value = '{0}'", "31"));
                web.ExecuteScript(string.Format("document.getElementById('telefone').value = '{0}'", "98879528"));
                web.ExecuteScript(string.Format("document.getElementById('email').value = '{0}'", "*****@*****.**"));

                web.ExecuteScript("document.getElementsByClassName('button clear col')[0].click();");
            }
            catch (Exception e)
            {
                RService.Log("Exception (FillForm) " + GetNameRobot() + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");
            }
        }
Пример #20
0
        /*Guarda numa lista os links dos arquivos de edital para um licitação*/
        private static List <string> FindDocLinks(string num)
        {
            RService.Log("(FindDocLinks) " + GetNameRobot() + ": Buscando editais da licitação.. " + num + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");

            List <string> links = new List <string>();

            try
            {
                int attachmentCount = 1;

                foreach (var ai in web.FindElements(By.TagName("img")))
                {
                    if (!string.IsNullOrEmpty(ai.GetAttribute("onclick")) && ai.GetAttribute("onclick").Contains("downloadAnexo"))
                    {
                        links.Add(string.Format(Constants.BB_LINK_ANEXO, num, attachmentCount));
                        attachmentCount++;
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (FindDocLinks) " + GetNameRobot() + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");
            }

            return(links);
        }
Пример #21
0
        /*Guarda numa lista o num e uf de cada licitação econtrada na pesquisa*/
        private static List <string> FindLicitNumsAndUfs(string innerHtml)
        {
            RService.Log("(FindLicitNumsAndUfs) " + Name + ": Buscando licitações.." + " at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                var numRx   = new Regex("detalhar\\(\\d+\\)");
                var stateRx = new Regex("UF: <b>\\w+<\\/b>");

                if (numRx.IsMatch(innerHtml) && stateRx.IsMatch(innerHtml))
                {
                    var numMatches   = numRx.Matches(innerHtml);
                    var stateMatches = stateRx.Matches(innerHtml);

                    for (int i = 0; i < numMatches.Count; i++)
                    {
                        string num   = numMatches[i].Value.Replace("detalhar(", "").Replace(")", "");
                        string uf    = stateMatches[i].Value.Replace("UF: <b>", "").Replace("</b>", "");
                        string numUf = num + ":" + uf;
                        numUFs.Add(numUf);
                    }
                }
                else
                {
                    RService.Log("(FindLicitNumsAndUfs) " + Name + ": Não foram encontradas licitações para análise at {0}", Path.GetTempPath() + Name + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (FindLicitNumsAndUfs) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(numUFs);
        }
Пример #22
0
        private static void GetCidades()
        {
            try
            {
                dicCidades = new Dictionary <string, string>();

                /*Acessa o site do TCE*/
                web.Navigate().GoToUrl(Constants.TCEPR_SITE);

                var element = web.FindElementByXPath("//select[@name='ctl00$ContentPlaceHolder1$ddlMunicipio']");
                var options = element.FindElements(By.TagName("option"));

                foreach (var item in options)
                {
                    if (!Regex.IsMatch(item.Text, @"Selecionar"))
                    {
                        dicCidades.Add(item.GetAttribute("value"), Regex.Replace(item.Text, @"\r", "").Trim());
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetCidades) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
Пример #23
0
        /*Faz o download de um arquivo usando um valor para o header UserAgent*/
        internal static void DownloadFileWebRequest(string url, string path, string fileName)
        {
            try
            {
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
                wr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
                var tempName = Guid.NewGuid().ToString();
                using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)wr.GetResponse())
                    using (Stream remote = myHttpWebResponse.GetResponseStream())
                        using (Stream local = File.Create(path + tempName))
                        {
                            byte[] buffer = new byte[1024];
                            int    bytesRead;

                            do
                            {
                                bytesRead = remote.Read(buffer, 0, buffer.Length);
                                local.Write(buffer, 0, bytesRead);
                            } while (bytesRead > 0);
                        }

                File.Move(path + tempName, path + fileName);
            }
            catch (Exception e)
            {
                RService.Log("RService Exception WebHandle: (DownloadFileWebRequest) [LinkFile : " + url + "] " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
            }
        }
Пример #24
0
        internal static void CreateABucket(IAmazonS3 client)
        {
            try
            {
                PutBucketRequest putRequest = new PutBucketRequest
                {
                    //Envia o pedido para criar o bucket (caso ele não exista), concedendo controle total para o dono
                    BucketName      = bucketName,
                    UseClientRegion = true,
                    Grants          = new List <S3Grant>
                    {
                        new S3Grant {
                            Grantee = new S3Grantee {
                                DisplayName = "contato"
                            }, Permission = S3Permission.FULL_CONTROL
                        }
                    }
                };

                //Cria o bucket na região especificada pelo cliente
                PutBucketResponse putResponse = client.PutBucket(putRequest);
            }
            catch (Exception e)
            {
                RService.Log("RService Exception AWS (CreateABucket): " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
            }
        }
Пример #25
0
        /*Método pelo qual o serviço inicia o robô no Timer agendado.*/
        internal static void InitCallBack(object state)
        {
            try
            {
                isRM = false;

                //Busca as informações do robô no banco de dados.
                config = ConfigRobotController.FindByName(Name);

                //Se o robô estiver ativo inicia o processamento.
                if (config.Active == 'Y')
                {
                    // Deleta o último arquivo de log.
                    if (File.Exists(Path.GetTempPath() + Name + ".txt"))
                    {
                        File.Delete(Path.GetTempPath() + Name + ".txt");
                    }

                    config.Status = 'R';
                    ConfigRobotController.Update(config);
                    using (FileStream fs = File.Create(Path.GetTempPath() + Guid.NewGuid().ToString() + ".ire")) { }
                    Init();

                    //Verifica se teve atualização
                    config = ConfigRobotController.FindByName(Name);

                    //Verifica quantas licitações foram coletadas nessa execução, grava em log.
                    config.NumLicitLast = NumLicitacoes;
                    RService.Log(Name + " find " + NumLicitacoes + " novas licitações at {0}", Path.GetTempPath() + Name + ".txt");
                    RService.Log(Name + " consumiu " + NumCaptcha + " captchas at {0}", Path.GetTempPath() + Name + ".txt");
                    NumLicitacoes = 0;

                    config.LastDate = DateTime.Now;
                }

                //Reprogamando a próxima execução do robô.
                RService.ScheduleMe(config);

                //Atualiza as informações desse robô.
                config.Status = 'W';
                ConfigRobotController.Update(config);

                //Arquivo que indica ao manager que é hora de atualizar as informações.
                File.Create(Path.GetTempPath() + Guid.NewGuid().ToString() + ".ire");
            }
            catch (Exception e)
            {
                RService.Log("Exception (InitCallBack) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");

                if (web != null)
                {
                    web.Close();
                }
            }

            RService.Log("Finished " + Name + " at {0}", Path.GetTempPath() + Name + ".txt");

            EmailHandle.SendMail(Path.GetTempPath() + Name + ".txt", Name);
        }
Пример #26
0
        //Métodos que controlam o envio de arquivos para o Amazon Simple Storage Service (S3)
        internal static bool SendObject(Licitacao l, string pathEditais, string fileName)
        {
            bool segundaTentativa = false;

            try
            {
                do
                {
                    //cria o bucket no cliente caso o bucket não exista
                    if (!AmazonS3Util.DoesS3BucketExist(s3Client, bucketName))
                    {
                        CreateABucket(s3Client);
                    }

                    //Reúne os dados necessários do arquivo
                    PutObjectRequest putRequest = new PutObjectRequest
                    {
                        BucketName = bucketName + "/licitacoes",
                        Key        = fileName,
                        FilePath   = pathEditais + fileName,
                        Grants     = new List <S3Grant>
                        {
                            new S3Grant {
                                Grantee = new S3Grantee {
                                    URI = "http://acs.amazonaws.com/groups/global/AllUsers"
                                }, Permission = S3Permission.READ
                            }
                        }/*,
                          * TagSet = new List<Tag>
                          * {
                          * new Tag {Key = "IdLicitacao", Value = l.Id.ToString() },
                          * new Tag {Key = "Lote", Value = l.Lote.Id.ToString() },
                          * new Tag {Key = "Fonte", Value = l.LinkSite }
                          * }*/
                    };

                    //Envia o arquivo para o bucket
                    PutObjectResponse putResponse = s3Client.PutObject(putRequest);
                    return(true);
                } while (segundaTentativa);
            }
            catch (Exception e)
            {
                RService.Log("RService Exception AWS (SendObject): " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");

                //Faz uma segunda tentativa de envio
                segundaTentativa = !segundaTentativa;
                if (segundaTentativa)
                {
                    RService.Log("AWS (SendObject): Segunda tentativa de envio... at {0}", Path.GetTempPath() + "RSERVICE" + ".txt");
                    Thread.Sleep(5000);
                }
                else
                {
                    return(false);
                }
            }
            return(false);
        }
Пример #27
0
        private static void GetArquivos(Licitacao licitacao)
        {
            if (!Directory.Exists(PathEditais))
            {
                Directory.CreateDirectory(PathEditais);
            }

            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(licitacao.LinkEdital);

            try
            {
                var fileLinks = web.FindElements(By.TagName("td"))
                                .Where(l => l.GetAttribute("headers") == "DOWNLOAD2")
                                .ToList();

                if (fileLinks.Count > 0)
                {
                    int count = 1;
                    foreach (var fileLink in fileLinks)
                    {
                        fileLink.Click();

                        //if (IsElementPresent(web, By.XPath("//*[@id=\"apex_dialog_" + count + "\"]/iframe")))
                        //{
                        //    fileLink.Click();
                        //}

                        string captchaToken = GetCaptchaToken(Constants.TCERS_DOCUMENTSITEKEY, web.Url);
                        web.SwitchTo().Frame(web.FindElement(By.XPath("//*[@id=\"apex_dialog_" + count + "\"]/iframe")));
                        string fileName = web.FindElement(By.XPath("//*[@id=\"P100_NM_ARQUIVO_DISPLAY\"]")).Text.Split('(')[0].Trim();
                        ((IJavaScriptExecutor)web).ExecuteScript(string.Format("document.getElementById('g-recaptcha-response').value='{0}'", captchaToken));
                        web.FindElement(By.XPath("//*[@id=\"P100_DOWNLOAD\"]")).Click();
                        Thread.Sleep(10000);
                        CreateArquivo(licitacao, fileName);
                        count++;
                        web.FindElement(By.TagName("html")).SendKeys(Keys.Escape);
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetArquivos) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
Пример #28
0
        private static void CreateItensLicitacao(HtmlDocument htmDoc, Licitacao licitacao)
        {
            RService.Log("(CreateItensLicitacao) " + Name + ": Criando itens do objeto da licitação num.. " + licitacao.IdLicitacaoFonte + " at {0}", Path.GetTempPath() + Name + ".txt");

            int      count;
            HtmlNode dadosOc;
            int      rows = 1;

            /*Pega o html da table com o id dgItensOc pra essa OC*/
            dadosOc = htmDoc.DocumentNode.Descendants().FirstOrDefault(x => x.Id == "ctl00_c_area_conteudo_grdv_item");
            /*Percorre as linhas da tabela exceto o Header que tem o atributo class HeaderStyle*/
            foreach (var row in dadosOc.Descendants("tr") /*.Where(x => x.Attributes.Contains("class") && !x.Attributes["class"].Value.Contains("HeaderSt"))*/)
            {
                if (!row.InnerHtml.Contains("th scope="))
                {
                    ItemLicitacao item = new ItemLicitacao();
                    /*Contador usado para as colunas da tabela*/
                    count = 0;
                    /*Percorre cada coluna de uma linha da tabela Intes da Oferta de Compra*/
                    foreach (var data in row.Descendants("td"))
                    {
                        /*A terceira coluna da tabela de Itens da Oferta de Compra contém a descrição do Item.*/
                        switch (count)
                        {
                        case 0:
                            break;

                        case 1:
                            item.Numero = int.Parse(data.InnerText.Trim());
                            break;

                        case 2:
                            item.Codigo = data.InnerText.Trim();
                            break;

                        case 3:
                            string desc = data.InnerText.Trim();
                            item.DescricaoDetalhada = desc;
                            item.Descricao          = desc.Length > 50 ? desc.Substring(0, 50) + "..." : desc;
                            break;

                        case 4:
                            item.Quantidade = int.Parse(data.InnerText.Trim());
                            break;

                        case 5:
                            item.Unidade = data.InnerText.Trim();
                            break;
                        }
                        count++;
                    }

                    item.MargemPreferencia = "0";
                    item.Decreto7174       = "0";
                    licitacao.ItensLicitacao.Add(item);
                    rows++;
                }
            }
        }
Пример #29
0
        public void Ctor__ScansAssembliesForSerivceTypes()
        {
            var expectedServiceType = typeof(SvcWithMethodRoute);

            var service = new RService(_options);

            service.ServiceTypes.Should().Contain(expectedServiceType);
        }
Пример #30
0
        public static Dictionary <string, Modalidade> GetNameToModalidade()
        {
            ModalidadeRepository            repo             = new ModalidadeRepository();
            Dictionary <string, Modalidade> nameToModalidade = new Dictionary <string, Modalidade>();

            try
            {
                foreach (Modalidade m in repo.FindAll())
                {
                    if (!nameToModalidade.ContainsKey(StringHandle.RemoveAccent(m.Modalidades.ToUpper())))
                    {
                        nameToModalidade.Add(StringHandle.RemoveAccent(m.Modalidades).ToUpper(), m);

                        if (m.Modalidades.Contains("RDC"))
                        {
                            nameToModalidade.Add("RDC ELETRONICO SRP", m);
                            nameToModalidade.Add("RDC ELETRONICO", m);
                            nameToModalidade.Add("RDC PRESENCIAL SRP", m);
                            nameToModalidade.Add("RDC PRESENCIAL", m);
                            nameToModalidade.Add("REGIME DIFERENCIADO DE CONTRATACOES", m);
                        }

                        if (m.Modalidades.Contains("Pregão Presencial") && !m.Modalidades.Contains("Pregão Presencial Internacional") && !nameToModalidade.ContainsKey("PREGAO PRESENCIAL - SRP"))
                        {
                            nameToModalidade.Add("PREGAO PRESENCIAL - SRP", m);
                        }

                        if (m.Modalidades.Contains("Carta Convite") && !m.Modalidades.Contains("Carta Convite Internacional") && !nameToModalidade.ContainsKey("CONVITE"))
                        {
                            nameToModalidade.Add("CONVITE", m);
                        }

                        if (m.Modalidades.Contains("Tomada de Preço") && !nameToModalidade.ContainsKey("TOMADA DE PRECOS"))
                        {
                            nameToModalidade.Add("TOMADA DE PRECOS", m);
                        }

                        if (m.Modalidades.Contains("Dispensa de Licitação") && !nameToModalidade.ContainsKey("PROCESSO DISPENSA"))
                        {
                            nameToModalidade.Add("PROCESSO DISPENSA", m);
                        }

                        if (!m.Modalidades.Contains("Concorrência - SRP") &&
                            !m.Modalidades.Contains("Concorrência Internacional") &&
                            m.Modalidades.Contains("Concorrência") && !nameToModalidade.ContainsKey("REGISTRO DE PRECOS (CONCORRENCIA)"))
                        {
                            nameToModalidade.Add("REGISTRO DE PRECOS (CONCORRENCIA)", m);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetModalidades) " + e.Message + " / " + e.StackTrace + " at {0}", Path.GetTempPath() + "RSERVICE.txt");
            }

            return(nameToModalidade);
        }