Ir para conteúdo
  • Cadastre-se

TimeB256

Membros Pro
  • Total de ítens

    70
  • Registro em

  • Última visita

Sobre TimeB256

Últimos Visitantes

O bloco dos últimos visitantes está desativado e não está sendo visualizado por outros usuários.

TimeB256's Achievements

Enthusiast

Enthusiast (6/14)

  • Dedicated Rare
  • Collaborator Rare
  • First Post
  • Conversation Starter
  • One Year In

Recent Badges

24

Reputação

3

Community Answers

  1. O erro não é relacionado a isso, conseguimos usar o certificado A3 normalmente para outras comunicações, inclusive mTLS com outros serviços, como um do Itaú. O erro se apresenta apenas quando fazendo a comunicação com a receita, e aquele fix na registry conserta esse problema especificamente, mas cria outros, mencionados no post original. Existe alguma solução alternativa conhecida que não causa efeitos colaterais?
  2. Bom dia, Vamos implementar um programa, que fará a captura das notas fiscais com certificado A3. No teste com Acbr, vimos um problema que está muito relacionado ao tópico abaixo: 7- Execute o FixCrypto_TLS1_2_Windows.reg. Fizemos os procedimentos, e realmente resolve o problema, mas identificamos que ao rodar, algumas coisas param de funcionar, como: - a conexão remota via RDP para de funcionar; - não conseguimos conectar no Marketplace do Visual Studio. - O SDK do Aws deixou de comunicar com os serviços Aws. Para desfazer, restauramos um backup das chaves alteradas, e os itens mencionados acima voltaram a funcionar, mas o erro de SSL voltou a acontecer. Vocês têm conhecimento disso ? Fizemos os testes em várias máquinas e realmente ocorreu. Segue parte do log paranoico. 16/01/25 08:50:12:991 - TLibNFeConfig.AplicarConfiguracoes - Feito 16/01/25 08:50:12:996 - Destravar 16/01/25 08:50:13:000 - SetRetorno(0, ) 16/01/25 08:50:13:008 - TACBrLibNFe.PrecisaCriptografar(DFe,SSLHttpLib) 16/01/25 08:50:13:014 - TACBrLibNFe.PrecisaCriptografar - Feito Result: False 16/01/25 08:50:13:018 - LIB_ConfigGravarValor(DFe, SSLHttpLib, 2) 16/01/25 08:50:13:023 - TACBrLibNFe.PrecisaCriptografar(DFe,SSLHttpLib) 16/01/25 08:50:13:030 - TACBrLibNFe.PrecisaCriptografar - Feito Result: False 16/01/25 08:50:13:034 - TLibNFeConfig.AjustarValor(tfGravar,DFe,SSLHttpLib,2) 16/01/25 08:50:13:038 - TLibNFeConfig.AjustarValor - Feito 16/01/25 08:50:13:043 - TLibNFeConfig.AplicarConfiguracoes: C:\Users\luis.felippe\source\keevo\acbr-rust\target\debug\ACBrLib.ini 16/01/25 08:50:13:049 - Travar 16/01/25 08:50:13:057 - TLibNFeConfig.AplicarConfiguracoes - Feito 16/01/25 08:50:13:062 - Destravar 16/01/25 08:50:13:067 - SetRetorno(0, ) 16/01/25 08:50:13:072 - TACBrLibNFe.PrecisaCriptografar(DFe,SSLXmlSignLib) 16/01/25 08:50:13:077 - TACBrLibNFe.PrecisaCriptografar - Feito Result: False 16/01/25 08:50:13:081 - LIB_ConfigGravarValor(DFe, SSLXmlSignLib, 4) 16/01/25 08:50:13:085 - TACBrLibNFe.PrecisaCriptografar(DFe,SSLXmlSignLib) 16/01/25 08:50:13:091 - TACBrLibNFe.PrecisaCriptografar - Feito Result: False 16/01/25 08:50:13:096 - TLibNFeConfig.AjustarValor(tfGravar,DFe,SSLXmlSignLib,4) 16/01/25 08:50:13:104 - TLibNFeConfig.AjustarValor - Feito 16/01/25 08:50:13:108 - TLibNFeConfig.AplicarConfiguracoes: C:\Users\luis.felippe\source\keevo\acbr-rust\target\debug\ACBrLib.ini 16/01/25 08:50:13:112 - Travar 16/01/25 08:50:13:116 - TLibNFeConfig.AplicarConfiguracoes - Feito 16/01/25 08:50:13:121 - Destravar 16/01/25 08:50:13:126 - SetRetorno(0, ) 16/01/25 08:50:13:130 - NFe_DistribuicaoDFePorUltNSU(31,33600491000160,0) 16/01/25 08:50:13:134 - Travar 16/01/25 08:50:13:139 - NFe_DistribuicaoDFePorUltNSU, Executar 16/01/25 08:50:23:994 - Destravar 16/01/25 08:50:23:994 - SetRetorno(-16, WebService Distribuição de DFe: - Inativo ou Inoperante tente novamente. Erro Interno: -2146893815 Erro HTTP: 0 URL: https://hom1.nfe.fazenda.gov.br/NFeDistribuicaoDFe/NFeDistribuicaoDFe.asmx Erro: 2148073481 - MotivoRetornadoDoWebService: "")
  3. Muito obrigado, muito esclarecedor. Pode fechar o post.
  4. Prezados, bom dia !! Eu gostaria de tirar algumas dúvidas acerca da configuração acbr. Eu tenho um projeto para captura de CTE. Toda vez que eu mudo de empresa, para realizar a captura, eu faço o seguinte código: Instancio a classe de serviço... acbrcteservico = new AcbrCTeServico(empresacteselecaomodel, certificadodigitalkeevo); E chamo o método de distribuicaoDfe var resposta = acbrcteservico.DistribuicaoDFe(); A minha dúvida é a seguinte... qdo instancio a classe, chamo o método ConfigurarCertificado. Esse método está todo descrito abaixo. 1) Gostaria de saber se está faltando alguma configuração que não foi passada.. 2) Ao final do método, eu chamo o acbrCTe.ConfigGravar(); É necessário ? 3) A propriedade acbrCTe.Config.Principal.LogPath é apenas caso eu queria gravar log ? 4) Eu preciso preencher a prop PathCTe ? Desde já agradeço a atenção !!! CÓDIGO DA CLASSE DE SERVICO (AcbrCTeServico) using Dfe.Pacotes.Infra.IntegracaoApi.Models.Passaporte; using Keevo.Pacotes.Infra.ACBrLib.Core.DFe; using Keevo.Pacotes.Infra.ACBrLib.CTe; using Keevo.Pacotes.Infra.ACBrLib.CTe.Models; using Keevo.Pacotes.Infra.Utils.Conversao; using Keevo.Pacotes.Infra.Utils.Criptografia; using Keevo.Pacotes.Infra.Utils.Diretorio; using Keevocenter.Pacotes.Infra.IntegracaoApi.Models.Certificado; namespace Dfe.Monitor.CapturaCte.Servicos { public class AcbrCTeServico : IDisposable { public ACBrCTe acbrcte { get; set; } public EmpresaParametrosCteSelecaoModel empresacte { get; set; } public CertificadoPorParametrosModel certificadodigitalkeevo { get; set; } public AcbrCTeServico(EmpresaParametrosCteSelecaoModel empresacte, CertificadoPorParametrosModel certificadodigitalkeevo) { try { acbrcte = new(); this.empresacte = empresacte; this.certificadodigitalkeevo = certificadodigitalkeevo; ConfigurarCertificado(acbrcte, certificadodigitalkeevo); } catch (Exception e) { Console.WriteLine($"AcbrCTeServico - Schemas: {acbrcte?.Config.PathSchemas} - StackTrace - {e.StackTrace}"); } } public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe() { Console.WriteLine($"Código NFE: {empresacte.codigonfe.ToInt()} - CNPJ: {empresacte.cnpj} - NSU: {empresacte.ultimonsu ?? ("0").PadLeft(15, '0')} Schemas: {acbrcte.Config.PathSchemas}"); return TratarDfeResposta(acbrcte.DistribuicaoDFe(empresacte.codigonfe.ToInt(), empresacte.cnpj, empresacte.ultimonsu ?? ("0").PadLeft(15, '0'), "")); } public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe(long ultimonsu) => DistribuicaoDFe(ultimonsu.ToString().PadLeft(15, '0')); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe(string ultimonsu) => TratarDfeResposta(acbrcte.DistribuicaoDFe(empresacte.codigonfe.ToInt(), empresacte.cnpj, ultimonsu, "")); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorNSU(long nsu) => DistribuicaoCtePorNSU(nsu.ToString().PadLeft(15, '0')); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorNSU(string nsu) => TratarDfeResposta(acbrcte.DistribuicaoDFePorNSU(empresacte.codigonfe.ToInt(), empresacte.cnpj, nsu)); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorChave(string chave) => DistribuicaoCtePorChave(empresacte, chave); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorChave(EmpresaParametrosCteSelecaoModel empresacte, string chave) => TratarDfeResposta(acbrcte.DistribuicaoDFePorChave(empresacte.codigonfe.ToInt(), empresacte.cnpj, chave)); public DistribuicaoDFeResposta<TipoCTe> TratarDfeResposta(string resposta) => DistribuicaoDFeResposta<TipoCTe>.LerResposta(resposta); public void ConfigurarCertificado() { ConfigurarCertificado(acbrcte, certificadodigitalkeevo); } public static void ConfigurarCertificado(ACBrCTe acbrCTe, CertificadoPorParametrosModel certificadodigitalkeevo) { acbrCTe.Config.DFe.SSLCryptLib = GetSSLCryptLib(); acbrCTe.Config.DFe.SSLHttpLib = GetSSLHttpLib(); acbrCTe.Config.DFe.SSLXmlSignLib = SSLXmlSignLib.xsLibXml2; acbrCTe.Config.DFe.DadosPFX = certificadodigitalkeevo.arquivocertificado; acbrCTe.Config.DFe.Senha = KeevoCrypto.Decrypt(certificadodigitalkeevo.senha); acbrCTe.Config.Ambiente = TipoAmbiente.taProducao; //acbrCTe.Config.SalvarArq = false; //acbrCTe.Config.SalvarGer = false; //Configurações para processamento acbrCTe.Config.SSLType = SSLType.LT_TLSv1_2; acbrCTe.Config.Timeout = 25000; acbrCTe.Config.AguardarConsultaRet = 0; acbrCTe.Config.Tentativas = 5; acbrCTe.Config.IntervaloTentativas = 1000; acbrCTe.Config.DFe.TimeZoneModo = TimezoneMode.tzManual; acbrCTe.Config.DFe.TimeZoneStr = "-03:00"; //acbrCTe.Config.PathSchemas = KeevoDiretorio.AppPath() + @"/Schemas/CTe"; acbrCTe.Config.PathSchemas = Path.Combine(KeevoDiretorio.AppPath(), "Schemas", "CTe"); //acbrCTe.Config.Principal.LogNivel = Keevo.Pacotes.Infra.ACBrLib.Core.NivelLog.logParanoico; //acbrCTe.Config.Principal.LogPath = KeevoDiretorio.AppPath(); acbrCTe.ConfigGravar(); } private static SSLCryptLib GetSSLCryptLib() => ACBrCTe.IsWindows ? SSLCryptLib.cryWinCrypt : SSLCryptLib.cryOpenSSL; private static SSLHttpLib GetSSLHttpLib() => ACBrCTe.IsWindows ? SSLHttpLib.httpWinHttp : SSLHttpLib.httpOpenSSL; public void Dispose() { acbrcte.Dispose(); } } }
  5. O certificado pelo banco não está vencido, de qualquer forma, irei excluir e reconfigurar. Obrigado, qualquer dúvida abro novo post.
  6. Bom dia a todos! Então, estou fazendo a captura de Ctes para uma determinada empresa, e apenas nela ocorre o erro abaixo: Estou passando como param para o DistribuicaoDFe os seguintes dados: codigonfe = 31 cnpjempresa = 34048121000125 ultimonse = 000000000000000 ArquivoOuXml= "" public string DistribuicaoDFe(int acUFAutor, string eCnpjcpf, string eultNsu, string ArquivoOuXml) System.ApplicationException: 'WebService Distribuição de DFe: - Inativo ou Inoperante tente novamente. Erro Interno: 0 Erro HTTP: 403 URL: https://www1.cte.fazenda.gov.br/CTeDistribuicaoDFe/CTeDistribuicaoDFe.asmx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>403 - Forbidden: Access is denied.</title> <style type="text/css"> <!-- body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;} fieldset{padding:0 15px 10px 15px;} h1{font-size:2.4em;margin:0;color:#FFF;} h2{font-size:1.7em;margin:0;color:#CC0000;} h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} #header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF; background-color:#555555;} #content{margin:0 0 0 2%;position:relative;} .content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} --> </style> </head> <body> <div id="header"><h1>Server Error</h1></div> <div id="content"> <div class="content-container"><fieldset> <h2>403 - Forbidden: Access is denied.</h2> <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3> </fieldset></div> </div> </body> </html> Trechos do código: public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe() => TratarDfeResposta(acbrcte.DistribuicaoDFe(empresacte.codigonfe.ToInt(), empresacte.cnpj, empresacte.ultimonsu ?? ("0").PadLeft(15, '0'), "")); public string DistribuicaoDFe(int acUFAutor, string eCnpjcpf, string eultNsu, string ArquivoOuXml) { int bufferLen = 256; StringBuilder buffer = new StringBuilder(bufferLen); CTE_DistribuicaoDFe method = GetMethod<CTE_DistribuicaoDFe>(); int ret = ExecuteMethod(() => method(libHandle, acUFAutor, ACBrLibHandle.ToUTF8(eCnpjcpf), ACBrLibHandle.ToUTF8(eultNsu), ACBrLibHandle.ToUTF8(ArquivoOuXml), buffer, ref bufferLen)); CheckResult(ret); return ProcessResult(buffer, bufferLen); } Desde já agradeço !
  7. Bom dia a todos; Gostaria de saber onde consigo baixar o ACBrNFCom? E se já esta adaptado para utilizarmos no VB6?
  8. Consegui capturar o mesmo erro, mas ele agora deu uma mensagem que não havia percebido: Notem o último erro. AcbrCTeServico - antes de instanciar acbrcte (dotnet:28): GLib-GObject-WARNING **: 16:38:30.221: cannot register existing type 'GdkDisplayManager' (dotnet:28): GLib-CRITICAL **: 16:38:30.221: g_once_init_leave: assertion 'result != 0' failed (dotnet:28): GLib-GObject-CRITICAL **: 16:38:30.221: g_object_new_with_properties: assertion 'G_TYPE_IS_OBJECT (object_type)' failed (dotnet:28): GLib-GObject-WARNING **: 16:38:30.221: invalid (NULL) pointer instance (dotnet:28): GLib-GObject-CRITICAL **: 16:38:30.221: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed (dotnet:28): GLib-GObject-WARNING **: 16:38:30.221: invalid (NULL) pointer instance (dotnet:28): GLib-GObject-CRITICAL **: 16:38:30.222: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed (dotnet:28): GLib-GObject-WARNING **: 16:38:30.222: cannot register existing type 'GdkDisplay' (dotnet:28): GLib-CRITICAL **: 16:38:30.222: g_once_init_leave: assertion 'result != 0' failed (dotnet:28): GLib-GObject-CRITICAL **: 16:38:30.222: g_type_register_static: assertion 'parent_type > 0' failed (dotnet:28): GLib-CRITICAL **: 16:38:30.223: g_once_init_leave: assertion 'result != 0' failed (dotnet:28): GLib-GObject-CRITICAL **: 16:38:30.223: g_object_new_with_properties: assertion 'G_TYPE_IS_OBJECT (object_type)' failed Segmentation fault (core dumped) xvfb-run: error: problem while cleaning up temporary directory
  9. O meu arquivo dockerfile está configurado da seguinte forma: Está faltando alguma instalação? Vi que no post do Julio Cavalcanti, temos instalação de itens a mais. #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base RUN apt update && apt-get install -y libxml2 libxslt-dev libgtk2.0-0 xvfb WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src COPY src/WebApis/Api.Dfe/*.csproj ./ COPY src/nuget.config ./ RUN dotnet restore "Api.Dfe.csproj" /p:Configuration="Release" --configfile "./nuget.config" COPY src/WebApis/Api.Dfe/ ./ WORKDIR "/src" RUN dotnet build "Api.Dfe.csproj" -c Release -o /app FROM build AS publish RUN dotnet publish "Api.Dfe.csproj" -c Release -o /app FROM base AS final WORKDIR /app COPY --from=publish /app . #https://stackoverflow.com/questions/60934639/install-fonts-in-linux-container-for-asp-net-core # RUN echo "deb http://deb.debian.org/debian/ bookworm main contrib" > /etc/apt/sources.list && \ # echo "deb-src http://deb.debian.org/debian/ bookworm main contrib" >> /etc/apt/sources.list && \ # echo "deb http://security.debian.org/ bookworm-security main contrib" >> /etc/apt/sources.list && \ # echo "deb-src http://security.debian.org/ bookworm-security main contrib" >> /etc/apt/sources.list RUN sed -i'.bak' 's/$/ contrib/' /etc/apt/sources.list RUN apt-get update; apt-get install -y ttf-mscorefonts-installer fontconfig # ENV DISPLAY :99 # RUN chmod 0755 /app/start.sh # ENTRYPOINT ["bash", "start.sh"] # ENTRYPOINT ["xvfb-run", "dotnet", "Api.Dfe.dll"] ENTRYPOINT ["/bin/sh", "-c", "/usr/bin/xvfb-run -a $@", ""] CMD ["dotnet", "Api.Dfe.dll"]
  10. Atualizei as dlls agora, vou testar e reporto.
  11. Então, vou realizar o seguinte teste.. O que entendemos é que a acbr quando instanciada, carrega umas bibliotecas gráficas (xvfb e GdkWindow). Hoje, tenho um arquivo na api e no monitor (start.sh), onde tenho seguinte conteúdo: #!/bin/bash if [ -f /tmp/.X99-lock ]; then rm /tmp/.X99-lock fi Xvfb :99 -screen 0 1280x1024x24 -ac +extension GLX +render -noreset & dotnet Api.Dfe.dll No dockerfile, faço a seguinte config. ENV DISPLAY :99 RUN chmod 0755 /app/start.sh ENTRYPOINT ["bash", "start.sh"] Vou comentar esse cara, e adicionar o seguinte comando; ENTRYPOINT ["xvfb-run", "dotnet", "ACBr.API.dll"] Vi isso no seguinte link: https://github.com/frones/ACBr/blob/5013dcaa92124d4516a471628d92042a8354c3f3/Projetos/ACBrLib/Demos/C%23/ACBr.API/ACBr.API/Dockerfile#L6 Não sei se irá resolver, mas vamos testar aqui. Tinha que ter uma forma de configurar pra acbr nao carregar essas bibliotecas gráficas.
  12. Bom dia Renato, Esse caso sempre ocorreu, como fizemos os logs, vimos que é justamente quando instancia a dll e a api cai. Toda infraestrutura é no linux, Ubuntu 22.04.4
  13. Boa noite, estou com um grande problema. Tenho um worker que fica capturando notas, manifestando, e ele roda em um container docker. Esse monitor comunica com uma API minha, por exemplo para realizar a manifestação da nota. Veja esse trecho do código: private ACBrNFe ACBrNFe; private async Task<bool> ManifestarNota(NotasFiscaisManifestacaoModel nota, en_tipomanifestacao tipomanifestacao) { Console.WriteLine("Método ManifestarNota - Segundo processo"); bool result = false; var empresa = await _repositorio.empresa.SelecionarAsync(nota.idempresaevocenter); Console.WriteLine($"Método ManifestarNota - Empresa: {empresa.razaosocial}"); CertificadoPorParametrosModel certificadodigitalkeevo = await _kcenterworkscertificadoservico.SelecionarPorParametros(nota.idempresaevocenter, nota.idmaster, AplicativoModel.en_aplicativo.Manifestacao.ToInt()); if (certificadodigitalkeevo == null) return false; Console.WriteLine($"Método ManifestarNota - Leu certificado: {certificadodigitalkeevo.datavalidade}"); //string caminhoCompleto = Path.Combine(Path.GetTempPath(), certificadodigitalkeevo.idcertificado.ToString() + ".pfx"); try { Console.WriteLine("Método ManifestarNota - Início config acbr"); ACBrNFe = new(); Console.WriteLine("Método ManifestarNota - Instanciou acbr"); ConfigurarCertificado(ACBrNFe, certificadodigitalkeevo); Console.WriteLine("Método ManifestarNota - Configurou certificado acbr"); } catch { return false; } O problema é o seguinte: Fui colocando log no monitor e para printar na AWS, e ocorre o seguinte erro quando passo nessa parte: ACBrNFe = new(); O erro é: 03 de setembro de 2024 às 16:36 (UTC-3:00) start.sh: line 7: 8 Segmentation fault (core dumped) dotnet Api.Dfe.dll bcdc131931024db48b613901b8f7788a dfe-api-prod 03 de setembro de 2024 às 16:36 (UTC-3:00) (dotnet:8): GLib-GObject-WARNING **: 19:36:05.505: cannot register existing type 'GdkWindow' bcdc131931024db48b613901b8f7788a dfe-api-prod 03 de setembro de 2024 às 16:36 (UTC-3:00) (dotnet:8): GLib-GObject-CRITICAL **: 19:36:05.505: g_object_new_with_properties: assertion 'G_TYPE_IS_OBJECT (object_type)' failed bcdc131931024db48b613901b8f7788a dfe-api-prod 03 de setembro de 2024 às 16:36 (UTC-3:00) (dotnet:8): GLib-GObject-WARNING **: 19:36:05.505: cannot register existing type 'GdkWindowImpl' bcdc131931024db48b613901b8f7788a dfe-api-prod 03 de setembro de 2024 às 16:36 (UTC-3:00) (dotnet:8): GLib-GObject-CRITICAL **: 19:36:05.505: g_type_interface_add_prerequisite: assertion 'G_TYPE_IS_INTERFACE (interface_type)' failed bcdc131931024db48b613901b8f7788a dfe-api-prod 03 de setembro de 2024 às 16:36 (UTC-3:00) (dotnet:8): GLib-GObject-CRITICAL **: 19:36:05.505: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed Por favor, conseguem me ajudar ?
  14. Boa tarde, então, vou te passar minha classe de serviço, como está configurada. Se puder me ajudar... Enviei 2 trechos de código pra ver se me ajuda. O primeiro é minha classe de serviço de config do Acbr. O segundo, toda vez que eu processo uma empresa na captura de cte, eu instancio essa classe. using Dfe.Pacotes.Infra.IntegracaoApi.Models.Passaporte; using Keevo.Pacotes.Infra.ACBrLib.Core.DFe; using Keevo.Pacotes.Infra.ACBrLib.CTe; using Keevo.Pacotes.Infra.ACBrLib.CTe.Models; using Keevo.Pacotes.Infra.Utils.Conversao; using Keevo.Pacotes.Infra.Utils.Criptografia; using Keevo.Pacotes.Infra.Utils.Diretorio; using Keevocenter.Pacotes.Infra.IntegracaoApi.Models.Certificado; namespace Dfe.Monitor.CapturaCte.Servicos { public class AcbrCTeServico : IDisposable { public ACBrCTe acbrcte { get; set; } public EmpresaParametrosCteSelecaoModel empresacte { get; set; } public CertificadoPorParametrosModel certificadodigitalkeevo { get; set; } public AcbrCTeServico(EmpresaParametrosCteSelecaoModel empresacte, CertificadoPorParametrosModel certificadodigitalkeevo) { acbrcte = new(); this.empresacte = empresacte; this.certificadodigitalkeevo = certificadodigitalkeevo; ConfigurarCertificado(acbrcte, certificadodigitalkeevo); } public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe() => TratarDfeResposta(acbrcte.DistribuicaoDFe(empresacte.codigonfe.ToInt(), empresacte.cnpj, empresacte.ultimonsu ?? ("0").PadLeft(15, '0'), "")); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe(long ultimonsu) => DistribuicaoDFe(ultimonsu.ToString().PadLeft(15, '0')); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoDFe(string ultimonsu) => TratarDfeResposta(acbrcte.DistribuicaoDFe(empresacte.codigonfe.ToInt(), empresacte.cnpj, ultimonsu, "")); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorNSU(long nsu) => DistribuicaoCtePorNSU(nsu.ToString().PadLeft(15, '0')); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorNSU(string nsu) => TratarDfeResposta(acbrcte.DistribuicaoDFePorNSU(empresacte.codigonfe.ToInt(), empresacte.cnpj, nsu)); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorChave(string chave) => DistribuicaoCtePorChave(empresacte, chave); public DistribuicaoDFeResposta<TipoCTe> DistribuicaoCtePorChave(EmpresaParametrosCteSelecaoModel empresacte, string chave) => TratarDfeResposta(acbrcte.DistribuicaoDFePorChave(empresacte.codigonfe.ToInt(), empresacte.cnpj, chave)); public DistribuicaoDFeResposta<TipoCTe> TratarDfeResposta(string resposta) => DistribuicaoDFeResposta<TipoCTe>.LerResposta(resposta); public void ConfigurarCertificado() { ConfigurarCertificado(acbrcte, certificadodigitalkeevo); } public static void ConfigurarCertificado(ACBrCTe acbrCTe, CertificadoPorParametrosModel certificadodigitalkeevo) { acbrCTe.Config.DFe.SSLCryptLib = GetSSLCryptLib(); acbrCTe.Config.DFe.SSLHttpLib = GetSSLHttpLib(); acbrCTe.Config.DFe.SSLXmlSignLib = SSLXmlSignLib.xsLibXml2; acbrCTe.Config.DFe.DadosPFX = certificadodigitalkeevo.arquivocertificado; acbrCTe.Config.DFe.Senha = KeevoCrypto.Decrypt(certificadodigitalkeevo.senha); acbrCTe.Config.Ambiente = TipoAmbiente.taProducao; acbrCTe.Config.SalvarArq = false; acbrCTe.Config.SalvarGer = false; //Configurações para processamento acbrCTe.Config.SSLType = SSLType.LT_TLSv1_2; acbrCTe.Config.Timeout = 25000; acbrCTe.Config.AguardarConsultaRet = 0; acbrCTe.Config.Tentativas = 5; acbrCTe.Config.IntervaloTentativas = 1000; acbrCTe.Config.PathSchemas = KeevoDiretorio.AppPath() + @"/Schemas/CTe"; //Configurações para logs //#if (DEBUG) acbrCTe.Config.Principal.LogNivel = Keevo.Pacotes.Infra.ACBrLib.Core.NivelLog.logParanoico; acbrCTe.Config.Principal.LogPath = KeevoDiretorio.AppPath(); acbrCTe.ConfigGravar(); //#endif } private static SSLCryptLib GetSSLCryptLib() => ACBrCTe.IsWindows ? SSLCryptLib.cryWinCrypt : SSLCryptLib.cryOpenSSL; private static SSLHttpLib GetSSLHttpLib() => ACBrCTe.IsWindows ? SSLHttpLib.httpWinHttp : SSLHttpLib.httpOpenSSL; public void Dispose() { acbrcte.Dispose(); } } } Toda vez que eu processo uma empresa, eu instancio essa classe, conforme código abaixo: public async Task ProcessarEmpresa(EmpresaParametrosCteSelecaoModel empresacteselecaomodel, SemaphoreSlim semaphoreempresa) { AcbrCTeServico? acbrcteservico = null; try { if (empresacteselecaomodel.datahoraultimaconsulta.AddHours(1).AddMinutes(1) > DateTime.Now.ToSATimeZone()) { _logger.LogInformation($"[MONITOR_CAPTURA_CTE][{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] A empresa está em no tempo de 1 hora de espera"); return; } CertificadoPorParametrosModel certificadodigitalkeevo = await _kcenterworkscertificadoservico.SelecionarPorParametros ( empresacteselecaomodel.idempresaevocenter, empresacteselecaomodel.idmaster, AplicativoModel.en_aplicativo.Manifestacao.ToInt() ); if (!ValidacaoCertificado(certificadodigitalkeevo, empresacteselecaomodel)) return; else { _logger.LogInformation($"[MONITOR_CAPTURA_CTE][{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] Iniciando processamento da empresa [{empresacteselecaomodel.idmaster}] - CNPJ: {empresacteselecaomodel.cnpj}, Razão Social: {empresacteselecaomodel.razaosocial}"); acbrcteservico = new AcbrCTeServico(empresacteselecaomodel, certificadodigitalkeevo); long ultimoNSUretornado = 0; long maxNSUretornado = 0; do { long ultimoNsuConsulta = Convert.ToInt64(empresacteselecaomodel.ultimonsu); var resposta = acbrcteservico.DistribuicaoDFe(); _logger.LogInformation($"[{DateTime.Now}][MONITOR_CAPTURA_CTE][{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] Resultado da busca para empresa [{empresacteselecaomodel.cnpj}:{empresacteselecaomodel.razaosocial}] | CStat: {resposta.CStat} - XMotivo: {resposta.XMotivo}"); if (resposta.CStat.Equals(DOCUMENTO_ENCONTRADO)) //DOCUMENDO ENCONTRADO 138 await ProcessarRespostaDistribuicaoDFe(resposta, empresacteselecaomodel); else if (resposta.CStat.Equals(CONSUMO_INDEVIDO) || resposta.CStat.Equals(CNPJ_DIGITAL)) //CONSUMO INDEVIDO = 656//CNPJ_DIGITAL = 593 return; ultimoNSUretornado = Convert.ToInt64(resposta.ultNSU); maxNSUretornado = Convert.ToInt64(resposta.maxNSU); _logger.LogInformation($"[MONITOR_CAPTURA_CTE][{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] Salvando novas informacoes da empresa [{empresacteselecaomodel.idmaster}] - CNPJ: {empresacteselecaomodel.cnpj}, Razão Social: {empresacteselecaomodel.razaosocial} ------- UltimoNSUEmpresa: {empresacteselecaomodel.ultimonsu} - MaxNSUSefaz: {resposta.maxNSU}/ultimoNSUSefaz:{resposta.ultNSU}"); await SalvarConfiguracaoParametrosEmpresaCte(empresacteselecaomodel, resposta.ultNSU); _logger.LogInformation($"[MONITOR_CAPTURA_CTE][{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] INFORMAÇÕES SALVAS [{empresacteselecaomodel.idmaster}] - CNPJ: {empresacteselecaomodel.cnpj}, Razão Social: {empresacteselecaomodel.razaosocial}"); if (ultimoNsuConsulta == maxNSUretornado) break; } while (ultimoNSUretornado <= maxNSUretornado); } } catch (Exception ex) { LogarException(ex, "ProcessarEmpresa"); } finally { //acbrcteservico?.Dispose(); try { semaphoreempresa.Release(); } catch (Exception e) { LogarException(e); } } } Se precisar de alguma outra informação, estou a disposição.
×
×
  • Criar Novo...

Informação Importante

Colocamos cookies em seu dispositivo para ajudar a tornar este site melhor. Você pode ajustar suas configurações de cookies, caso contrário, assumiremos que você está bem para continuar.