Guest User

Untitled

a guest
Dec 19th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.66 KB | None | 0 0
  1. //R-1000
  2. public bool EnvioEventoevtInfoContribuinte(Empresa objEmpresa, DateTime periodoApuracao)
  3. {
  4. try
  5. {
  6.  
  7. EventosREINF auxiliar = new EventosREINF();
  8. _reinf.evtInfoContri = auxiliar.EnviarEvtInfoContri(objEmpresa, periodoApuracao);
  9. ReinfEvtInfoContri evtInfoContri = _reinf.evtInfoContri;
  10.  
  11.  
  12. //serializa o evento informações do Contribuinte
  13. string xmlEventoInclusao = XMLConverte.SerializaObjeto<ReinfEvtInfoContri>(evtInfoContri);
  14.  
  15. //Exibe a lista de certificados para o usuário selecionar
  16. X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();
  17.  
  18. //Adiciona a assinatura digital ao evento
  19. XmlDocument xmlDoc = new XmlDocument();
  20. Assinar(xmlDoc, oX509Cert, xmlEventoInclusao);
  21.  
  22. //XmlDocument xmlReinf = Assinar(xmlEventoInclusao, oX509Cert);
  23.  
  24. //Inicializa o vetor de eventos do lote a ser enviado
  25. REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = new REINF.Model.v1_04.TArquivoeReinf[1];
  26.  
  27. //Adicionar Arquivo XML ao array de Eventos do Lote
  28. REINF.Model.v1_04.TArquivoeReinf arquivoR_1000 = new REINF.Model.v1_04.TArquivoeReinf
  29. {
  30. id = objEmpresa.ToString(),
  31. Any = xmlDoc.DocumentElement
  32. };
  33. xmlsEvento[0] = arquivoR_1000;
  34.  
  35. //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
  36. XmlDocument xmlDocEventoEnvio = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);
  37.  
  38. //Envia arquivo xml para o web service e obtém o xml de retorno
  39. XmlElement xmlRetorno = EnviarXML(xmlDocEventoEnvio, oX509Cert);
  40. }
  41. catch
  42. {
  43. throw;
  44. }
  45. return true;
  46. }
  47.  
  48. //R-2010
  49. public bool EnvioEventoevtServTom(List<NotaFiscal> objNotasFiscais, Empresa objEmpresa, DateTime periodoApuracao)
  50. {
  51. try
  52. {
  53. ReinfEvtServTom reinfEvtServTom = new ReinfEvtServTom();
  54.  
  55. EventosREINF auxiliar = new EventosREINF();
  56.  
  57. _reinf.evtServTom = auxiliar.EnviarevtServTom(objNotasFiscais, objEmpresa, periodoApuracao);
  58.  
  59. //Exibe a lista de certificados para o usuário selecionar
  60. X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();
  61.  
  62. //Inicializa o vetor de eventos do lote a ser enviado
  63. REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = ComunicacaoREINF(objNotasFiscais, oX509Cert).ToArray();
  64.  
  65. //Adicionar Arquivo XML ao array de Eventos do Lote
  66. REINF.Model.v1_04.TArquivoeReinf arquivoR_2010 = new REINF.Model.v1_04.TArquivoeReinf
  67. {
  68. id = objEmpresa.ToString(),
  69. };
  70. xmlsEvento[0] = arquivoR_2010;
  71.  
  72. //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
  73. XmlDocument xmlR2010 = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);
  74.  
  75. //Envia arquivo xml para o web service e obtém o xml de retorno
  76. XmlElement xmlRetorno = EnviarXML(xmlR2010, oX509Cert);
  77.  
  78. //Converte o xml de retorno para a classe retorno de envio
  79. ReinfRetornoLoteEventos reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno.OuterXml);
  80.  
  81.  
  82. }
  83. catch
  84. {
  85.  
  86. throw;
  87. }
  88. return true;
  89. }
  90.  
  91. //R-2020
  92. public bool EnvioEventoevtServPrest(List<NotaFiscal> objNotasFiscais, Empresa objEmpresa, DateTime periodoApuracao)
  93. {
  94. try
  95. {
  96.  
  97. ReinfEvtServPrest reinfEvtServPrest = new ReinfEvtServPrest();
  98.  
  99. EventosREINF auxiliar = new EventosREINF();
  100.  
  101. _reinf.evtServPrest = auxiliar.EnviarevtServPrest(objNotasFiscais, objEmpresa, periodoApuracao);
  102.  
  103. //Exibe a lista de certificados para o usuário selecionar
  104. X509Certificate2 oX509Cert = BuscarCertificadoEmpresa();
  105.  
  106. //Inicializa o vetor de eventos do lote a ser enviado
  107. REINF.Model.v1_04.TArquivoeReinf[] xmlsEvento = ComunicacaoREINF(objNotasFiscais, oX509Cert).ToArray();
  108.  
  109. //Adicionar Arquivo XML ao array de Eventos do Lote
  110. REINF.Model.v1_04.TArquivoeReinf arquivoR_2020 = new REINF.Model.v1_04.TArquivoeReinf
  111. {
  112. id = objEmpresa.ToString(),
  113. };
  114. xmlsEvento[0] = arquivoR_2020;
  115.  
  116. //Adiciona o xml do evento de informações do Contribuinte ao xml do evento de envio
  117. XmlDocument xmlR2100 = AdicionarLoteAoEventoEnvio(xmlsEvento, objEmpresa);
  118.  
  119. //Envia arquivo xml para o web service e obtém o xml de retorno
  120. XmlElement xmlRetorno = EnviarXML(xmlR2100, oX509Cert);
  121.  
  122. //Converte o xml de retorno para a classe retorno de envio
  123. ReinfRetornoLoteEventos reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno.OuterXml);
  124.  
  125.  
  126. }
  127. catch
  128. {
  129.  
  130. throw;
  131. }
  132. return true;
  133. }
  134.  
  135. private List<TArquivoeReinf> ComunicacaoREINF(List<NotaFiscal> objNotasFiscais, X509Certificate2 oX509Cert)
  136. {
  137. List<TArquivoeReinf> loteEnvio = new List<TArquivoeReinf>();
  138.  
  139. foreach (NotaFiscal notaFiscal in objNotasFiscais)
  140. {
  141. ReinfLoteEventos reinfLoteEventos = new ReinfLoteEventos();
  142.  
  143. string xmlEventoInfoContribuinte = XMLConverte.SerializaObjeto<ReinfLoteEventos>(reinfLoteEventos);
  144.  
  145. var xmlDoc = new XmlDocument();
  146. xmlDoc.LoadXml(xmlEventoInfoContribuinte);
  147.  
  148.  
  149. TArquivoeReinf ObjArqXmlFilho = new TArquivoeReinf
  150. {
  151. id = notaFiscal.TipoDocumento.Id.ToString(),
  152. Any = xmlDoc.DocumentElement
  153. };
  154.  
  155. loteEnvio.Add(ObjArqXmlFilho);
  156. }
  157. return loteEnvio;
  158. }
  159.  
  160. public ReinfRetornoLoteEventos RetornoLoteEventos(ReinfRetornoLoteEventos retornoLoteEventosInicial, string xmlRetorno)
  161. {
  162.  
  163. try
  164. {
  165. ReinfRetornoLoteEventos reinfRetornoLoteEventos = new ReinfRetornoLoteEventos();
  166. reinfRetornoLoteEventos = XMLConverte.DeserializaObjeto<ReinfRetornoLoteEventos>(xmlRetorno);
  167.  
  168.  
  169. ReinfRetornoLoteEventosRetornoEventos reinfRetornoLoteEventosRetornoEventos = new ReinfRetornoLoteEventosRetornoEventos
  170. {
  171. evento = reinfRetornoLoteEventos.retornoEventos.evento
  172. };
  173.  
  174.  
  175. REINF.Model.ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequest consultaInformacoesConsolidadasRequest = new ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequest
  176. {
  177. Body = new ConsultaEvento_ProducaoRestrita.ConsultaInformacoesConsolidadasRequestBody()
  178. };
  179. //consultaInformacoesConsolidadasRequest.Body.numeroInscricaoContribuinte = "";
  180. //consultaInformacoesConsolidadasRequest.Body.numeroProtocoloFechamento = "";
  181. //consultaInformacoesConsolidadasRequest.Body.tipoInscricaoContribuinte = "";
  182.  
  183. REINF.Model.ConsultaEvento_ProducaoRestrita.ConsultasReinfClient consultasReinfClient = new ConsultaEvento_ProducaoRestrita.ConsultasReinfClient();
  184.  
  185. }
  186. catch
  187. {
  188. throw;
  189. }
  190. return retornoLoteEventosInicial;
  191. }
  192.  
  193. private XmlDocument AdicionarLoteAoEventoEnvio(TArquivoeReinf[] xmlsEvento, Empresa objEmpresa)
  194. {
  195. //Leiaute Mensagem Entrada
  196. ReinfLoteEventos reinfLoteEventos = new ReinfLoteEventos
  197. {
  198. evento = new TArquivoeReinf[1]
  199. };
  200. reinfLoteEventos.evento = xmlsEvento;
  201.  
  202. //Serializa objeto evento de envio
  203. string xmlEventoEnvio = XMLConverte.SerializaObjeto<ReinfLoteEventos>(reinfLoteEventos);
  204.  
  205. //Converte xml do evento envio para XMLDocumente que será transmitido para o web service
  206. XmlDocument xmlDocEventoEnvio = XMLConverte.ConverterXMLParaXMLDocument(xmlEventoEnvio);
  207.  
  208. return xmlDocEventoEnvio;
  209. }
  210.  
  211. private static string UTF8ByteArrayToString(byte[] characters)
  212. {
  213. UTF8Encoding encoding = new UTF8Encoding();
  214. string constructedString = encoding.GetString(characters);
  215. return (constructedString);
  216. }
  217.  
  218. public void Assinar(XmlDocument xmlDoc, X509Certificate2 X509Cert, string xmlEventoInclusao)
  219. {
  220.  
  221.  
  222. // Cria o objeto SignedXml baseado no XmlDocument passado.
  223. SignedXml signedXml = new SignedXml(xmlDoc);
  224. signedXml.SigningKey = X509Cert.PrivateKey;
  225. signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
  226.  
  227. // Checa se foi informado um URI para a referência, se foi acrescenta o "#" no começo.
  228. xmlEventoInclusao = String.IsNullOrEmpty(xmlEventoInclusao) ? "" : $"#{xmlEventoInclusao}";
  229.  
  230. Reference reference = new Reference(xmlEventoInclusao);
  231. reference.Id = _reinf.evtInfoContri.id;
  232. reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
  233. reference.AddTransform(new XmlDsigC14NTransform());
  234. reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
  235.  
  236. signedXml.AddReference(reference);
  237.  
  238. // Carrega o certificado em um objeto KeyInfoX509Data e o adiciona ao objeto KeyInfo.
  239. KeyInfo KeyInfo = new KeyInfo();
  240. KeyInfo.AddClause(new KeyInfoX509Data(X509Cert));
  241. signedXml.KeyInfo = KeyInfo;
  242.  
  243. // Calcula a assinatura.
  244. signedXml.ComputeSignature();
  245.  
  246. // Obtém a representação XML da assinatura e a armazena em um objeto XmlElement.
  247. XmlElement xmlDigitalSignature = signedXml.GetXml();
  248.  
  249. // Acrescenta o elemento ao documento XML.
  250. xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
  251.  
  252. // Se o primeiro nó do documento for o nó de declaração XML
  253. // '<?xml version="1.0" encoding="utf-8"?>', remove ele.
  254. if (xmlDoc.FirstChild is XmlDeclaration)
  255. xmlDoc.RemoveChild(xmlDoc.FirstChild);
  256. }
  257.  
  258.  
  259.  
  260. private X509Certificate2 BuscarCertificadoEmpresa()
  261. {
  262. X509Certificate2 cert = null;
  263. ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
  264.  
  265. X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
  266. store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
  267. X509Certificate2Collection certcollection = (X509Certificate2Collection)store.Certificates;
  268. // pick a certificate from the store
  269. cert = X509Certificate2UI.SelectFromCollection(certcollection,
  270. "Autenticação do Certificado",
  271. "Informe um certificao válido", X509SelectionFlag.SingleSelection)[0];
  272.  
  273. store.Close();
  274.  
  275. return cert;
  276. }
  277.  
  278. private XmlElement EnviarXML(XmlDocument xmlDocEventoEnvio, X509Certificate2 oX509Cert)
  279. {
  280. XmlElement xmlResult = null;
  281.  
  282. var urlServicoEnvio = @"https://preprodefdreinf.receita.fazenda.gov.br/wsreinf/RecepcaoLoteReinf.svc";
  283. var address = new EndpointAddress(urlServicoEnvio);
  284. var binding = new BasicHttpsBinding();
  285.  
  286. // Informa que será usado um certificado digital para acessar o serviço.
  287. binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
  288. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  289.  
  290. // Cria o objeto cliente (do tipo System.ServiceModel.ClientBase) para acesso ao WebService.
  291. var recepcaoLoteReinfClient = new RecepcaoLoteReinfClient(binding, address);
  292.  
  293. // Passa o certificado digital para o objeto do tipo System.ServiceModel.ClientBase.
  294. recepcaoLoteReinfClient.ClientCredentials.ClientCertificate.Certificate = oX509Cert;
  295.  
  296. // Chama o WebService de fato, passando o XML do lote.
  297. recepcaoLoteReinfClient.Open();
  298.  
  299. // O método espera um objeto do tipo XElement, e retorna outro objeto XElement.
  300. //xmlResult = recepcaoLoteReinfClient.ReceberLoteEventos(xmlDoc.DocumentElement);
  301. var retornoEnvioXElement = recepcaoLoteReinfClient.ReceberLoteEventos((XElement.Parse(xmlDocEventoEnvio.OuterXml)));
  302. recepcaoLoteReinfClient.Close();
  303.  
  304. return xmlResult;
  305.  
  306. }
  307.  
  308. private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  309. {
  310. // If the certificate is a valid, signed certificate, return true.
  311. if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
  312. {
  313. return true;
  314. }
  315.  
  316. Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
  317. certificate.Subject,
  318. sslPolicyErrors.ToString());
  319.  
  320. return false;
  321. }
  322.  
  323. reference.Id = _reinf.evtInfoContri.id;
  324.  
  325. reference.Id = "#" + _reinf.evtInfoContri.id;
Add Comment
Please, Sign In to add comment