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");
            }
        }
Exemple #2
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);
            }
        }
 /*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");
     }
 }
        /*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);
        }
        private static void GetItens(HtmlDocument htmlQuote, Licitacao l)
        {
            try
            {
                foreach (var row in htmlQuote.DocumentNode.Descendants("tr").Where(x => !x.Attributes.Contains("height") && x.Attributes.Contains("class") && x.Attributes["class"].Value.Equals("tex3")))
                {
                    ItemLicitacao item  = new ItemLicitacao();
                    int           count = 0;

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

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

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

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

                    l.ItensLicitacao.Add(item);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetItens) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
        /*Cria os objetos Licitacao, Lote e LicitacaoArquivo fazendo as verificações necessárias.*/
        private static void HandleCreate(HtmlDocument htmlDoc, string ocnum, string situacao)
        {
            try
            {
                Regex  regex = new Regex("\\d{4}OC");
                string ocn   = ocnum;
                ocnum = "1" + regex.Replace(ocnum, DateTime.Now.ToString("yy"));

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

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

                        HtmlDocument htmlEditais   = WebHandle.GetHtmlDocOfPage(licitacao.LinkEdital);
                        int          numeroArquivo = 2;
                        //Faz o download de todos os arquivos do edital
                        foreach (HtmlNode editais in htmlEditais.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("href") && x.Attributes["href"].Value.Contains("ctl00$conteudo$WUC_Documento1$dgDocumento")))
                        {
                            DownloadEditais(licitacao.LinkEdital, GetFormParametersEdital(htmlEditais, numeroArquivo));
                        }
                        CreateLicitacaoArquivo(licitacao);
                        NumLicitacoes++;
                    }
                    else
                    {
                        RService.Log("Exception (HandleCreate) " + Name + ": A licitação não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                }
                else if (!string.IsNullOrEmpty(ocn) && LicitacaoController.ExistsBEC(ocn) && LicitacaoController.SituacaoAlteradaBEC(ocn, situacao))
                {
                    int id = LicitacaoController.GetIdByObservacoes(ocn);
                    LicitacaoController.UpdateSituacaoByIdLicitacao(id, situacao);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
        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");
            }
        }
Exemple #9
0
        private static void HandleTermoHomologacao(string licitInfo, Licitacao licitacao)
        {
            try
            {
                var nums = HandleLicitInfo(licitInfo);

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

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

                foreach (var grupo in grupos)
                {
                    GetPrecos(grupo, licitacao);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleTermoHomologacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
        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 void ConsultaAtaPregao(Licitacao licitacao)
        {
            RService.Log("(ConsultaAtaPregao) " + Historic + ": Buscando itens da ata do pregão at {0}", Path.GetTempPath() + Historic + ".txt");
            try
            {
                if (!string.IsNullOrEmpty(licitacao.Uasg) && !string.IsNullOrEmpty(licitacao.NumPregao))
                {
                    List <LicitacaoHistorico> itens = new List <LicitacaoHistorico>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    if (LicitacaoHistoricoController.Insert(historico))
                                    {
                                        NumHistoricos++;
                                    }
                                }
                                catch (Exception e)
                                {
                                    RService.Log("Exception (ConsultaAtaPregao) getMensagem " + Historic + " para a licitacao " + licitacao.IdLicitacaoFonte + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
                                }
                            }
                        }
                    }
                    else
                    {
                        RService.Log("(ConsultaAtaPregao) " + Historic + ": Pregão não contém ata pois não foi encerrado at {0}", Path.GetTempPath() + Historic + ".txt");
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (ConsultaAtaPregao) " + Historic + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
            }
        }
        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);
            }
        }
        /*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);
                }
            }
        }
        /*Cria uma nova licitacao.*/
        private static Licitacao CreateLicitacao(HtmlDocument htmDoc, string ocnum, string situacao)
        {
            RService.Log("(CreateLicitacao) " + Name + ": Criando licitação.. " + ocnum + " at {0}", Path.GetTempPath() + Name + ".txt");
            Licitacao licitacao = new Licitacao();

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

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

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

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

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

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

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

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

            return(LicitacaoController.IsValid(licitacao, out mensagemErro) ? licitacao : null);
        }