示例#1
0
        public string ConsultaCFDIRelacionadosRequest(string RfcPacEnviaSolicitud, string RfcReceptor, string RfcEmisor, string Uuid)
        {
            AccesoServicios ser           = new AccesoServicios();
            IList           uuidsCancelar = new List <string>();

            uuidsCancelar.Add(Uuid.ToUpper());
            string result;

            using (new NtLinkLocalServiceEntities())
            { string        path = "";
              NtLinkEmpresa nle  = new NtLinkEmpresa();
              if (!string.IsNullOrEmpty(RfcEmisor))
              {
                  empresa empresa = nle.GetByRfc(RfcEmisor);
                  SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata2 = new SAT.CFDI.Cliente.Procesamiento.Encabezado(RfcEmisor, this.FechaHoy(), uuidsCancelar);
                  path = Path.Combine(ConfigurationManager.AppSettings["Resources"], RfcEmisor);
                  string pathCer = Path.Combine(path, "Certs", "csd.cer");
                  string pathKey = Path.Combine(path, "Certs", "csd.key");
                  string pass    = empresa.PassKey;
                  SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType asignature = ser.Asignature(pathKey, encLMetadata2, pass, pathCer);
                  result = ser.ConsultaCFDIRelacionadosRequest(RfcPacEnviaSolicitud, RfcReceptor, RfcEmisor, Uuid, asignature);
              }
              else
              {
                  empresa empresa = nle.GetByRfc(RfcReceptor);
                  SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata2 = new SAT.CFDI.Cliente.Procesamiento.Encabezado(RfcReceptor, this.FechaHoy(), uuidsCancelar);
                  path = Path.Combine(ConfigurationManager.AppSettings["Resources"], RfcReceptor);
                  string pathCer = Path.Combine(path, "Certs", "csd.cer");
                  string pathKey = Path.Combine(path, "Certs", "csd.key");
                  string pass    = empresa.PassKey;
                  SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType asignature = ser.Asignature(pathKey, encLMetadata2, pass, pathCer);
                  result = ser.ConsultaCFDIRelacionadosRequest(RfcPacEnviaSolicitud, RfcReceptor, RfcEmisor, Uuid, asignature);
              } }
            return(result);
        }
        private string ArmarXmlPreFirma(Encabezado encLMetadata)
        {
            string str = string.Concat(new string[]
            {
                "<?xml version=\"1.0\"?><Cancelacion xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RfcEmisor=\"",
                HttpUtility.HtmlEncode(encLMetadata.RfcEmisor),
                "\" Fecha=\"",
                encLMetadata.FechaString,
                "\" xmlns=\"http://cancelacfd.sat.gob.mx\">"
            });

            str = encLMetadata.LisMListaFolios.Cast <object>().Aggregate(str, (string current, object elemento) => current + "<Folios><UUID>" + elemento.ToString() + "</UUID></Folios>");
            return(str + "</Cancelacion>");
        }
示例#3
0
        public int CancelarOtrosPACs(string uuid, string rfc, ref string respuesta, ref string acuse, string Base64Cer, string Base64Key, string PasswordKey)
        {
            int result;

            try
            {
                Cancelador.Logger.Info("Cancelando comprobante: " + uuid);
                IList uuidsCancelar = new List <string>();
                uuidsCancelar.Add(uuid.ToUpper());
                using (new NtLinkLocalServiceEntities())
                {
                    NtLinkEmpresa nle = new NtLinkEmpresa();


                    string pass = PasswordKey;
                    SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata2          = new SAT.CFDI.Cliente.Procesamiento.Encabezado(rfc, this.FechaHoy(), uuidsCancelar);
                    SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse ac2 = null;
                    acuse = this.EnviarCancelacionSATOtrosPACs(encLMetadata2, Base64Key, pass, Base64Cer, ref ac2);
                    if (string.IsNullOrEmpty(acuse))
                    {
                        acuse = "No se pudo conectar al servicio de cancelación del SAT";
                    }
                    int intEstatus2 = this.TraerEstatusSAT(uuid, ac2);
                    if (intEstatus2 != 201 && intEstatus2 != 202)
                    {
                        Cancelador.Logger.Error(acuse);
                        respuesta = intEstatus2 + " - " + Constantes.ErroresValidacion[intEstatus2];
                        throw new FaultException(respuesta);
                    }
                    Cancelador.Logger.Info(acuse);
                    string directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"], ac2.RfcEmisor, ac2.Fecha.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    string fileName = Path.Combine(directorio, "Cancelacion_" + uuid.ToString() + ".xml");
                    File.WriteAllText(fileName, acuse, Encoding.UTF8);
                    respuesta = intEstatus2 + " - " + Constantes.ErroresValidacion[intEstatus2];
                    result    = intEstatus2;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                Cancelador.Logger.Error("(cancelar) Error: " + ex.Message + ((ex.InnerException == null) ? "" : ("\nExcepción Interna:" + ex.InnerException.Message)));
                throw;
            }
        }
        private Acuse EnviarCFDIalSAT(Encabezado encLMetadata)
        {
            string strMAcuseRecibo = "";

            try
            {
                AccesoServicios accesoServicios = new AccesoServicios();
                accesoServicios.ClienteAutenticacion.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigurationManager.AppSettings["RutaSATAutenticacion"]);
                accesoServicios.ClienteRecepcion.Endpoint.Address     = new System.ServiceModel.EndpointAddress(ConfigurationManager.AppSettings["RutaSATRecepcion"]);

                var acuse = accesoServicios.EnviarBloqueCfdi(encLMetadata);
                return(acuse);
            }
            catch (Exception err)
            {
                Log.Error("(EnviarCFDIalSAT) Error al intentar enviar la información al SAT, Err:" + err.ToString() + "\r\nAcuse: " + strMAcuseRecibo);
                return(null);
            }
        }
示例#5
0
        public string ProcesarRespuestaAceptacionRechazo(string RfcReceptor, string RfcPacEnviaSolicitud, List <Folios> F)
        {
            AccesoServicios ser           = new AccesoServicios();
            IList           uuidsCancelar = new List <string>();

            foreach (Folios f in F)
            {
                uuidsCancelar.Add(f.UUDI.ToUpper());
            }
            List <SolicitudAceptacionRechazoFolios> Folio = new List <SolicitudAceptacionRechazoFolios>();

            foreach (Folios f in F)
            {
                SolicitudAceptacionRechazoFolios x = new SolicitudAceptacionRechazoFolios();
                x.UUID = f.UUDI;
                if (f.Respuesta.ToString() == "Aceptacion")
                {
                    x.Respuesta = TipoAccionPeticionCancelacion.Aceptacion;
                }
                else
                {
                    x.Respuesta = TipoAccionPeticionCancelacion.Rechazo;
                }
                Folio.Add(x);
            }
            string result;

            using (new NtLinkLocalServiceEntities())
            {
                NtLinkEmpresa nle     = new NtLinkEmpresa();
                empresa       empresa = nle.GetByRfc(RfcReceptor);
                string        fecha   = this.FechaHoy();
                SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata2 = new SAT.CFDI.Cliente.Procesamiento.Encabezado(RfcReceptor, fecha, uuidsCancelar);
                string path    = Path.Combine(ConfigurationManager.AppSettings["Resources"], RfcReceptor);
                string pathCer = Path.Combine(path, "Certs", "csd.cer");
                string pathKey = Path.Combine(path, "Certs", "csd.key");
                string pass    = empresa.PassKey;
                SAT.CFDI.Cliente.Procesamiento.ServicioAceptacionRechazo.SignatureType asignature = ser.AsignatureProceso(pathKey, encLMetadata2, pass, pathCer);
                result = ser.ProcesarRespuestaAceptacionRechazo(RfcReceptor, fecha, RfcPacEnviaSolicitud, Folio, asignature);
            }
            return(result);
        }
示例#6
0
        private string EnviarCancelacionSATOtrosPACs(SAT.CFDI.Cliente.Procesamiento.Encabezado metadata, string Base64Key, string passPrivada, string Base64Cer, ref SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse cAcuse)
        {
            string result;

            try
            {
                AccesoServicios accesoServicios = new AccesoServicios();
                SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse acuse = null;
                string acuseRecibo = accesoServicios.CancelarBloqueCfdiOtrosPACs(string.Empty, string.Empty, metadata, Base64Key, passPrivada, Base64Cer, ref acuse);
                cAcuse = acuse;
                Cancelador.Logger.Info(acuseRecibo);
                result = acuseRecibo;
            }
            catch (Exception ex)
            {
                Cancelador.Logger.Error("(EnviarCancelacionSAT) Error: " + ex.Message + ((ex.InnerException == null) ? "" : ("\nExcepción Interna:" + ex.InnerException.Message)));
                throw ex;
            }
            return(result);
        }
示例#7
0
        public int Cancelar(string uuid, string rfc, ref string respuesta, ref string acuse)
        //  public int Cancelar(string uuid, int idempresa, ref string respuesta, ref string acuse)
        {
            int result;

            try
            {
                Cancelador.Logger.Info("Cancelando comprobante: " + uuid);
                IList uuidsCancelar = new List <string>();
                uuidsCancelar.Add(uuid.ToUpper());
                using (new NtLinkLocalServiceEntities())
                {
                    NtLinkEmpresa nle     = new NtLinkEmpresa();
                    empresa       empresa = nle.GetByRfc(rfc);
                    // empresa empresa = nle.GetById(idempresa);
                    if (empresa == null)
                    {
                        respuesta = "300 - El usuario con el que se quiere conectar es inválido";
                        acuse     = "";
                        result    = 300;
                    }
                    else
                    {
                        NtLinkTimbrado tim    = new NtLinkTimbrado();
                        TimbreWs33     timbre = tim.ObtenerTimbre(uuid);
                        if (timbre == null)
                        {
                            TimbreWsHistorico timbreHist = tim.ObtenerTimbreHist(uuid);
                            if (timbreHist == null)
                            {
                                string path    = Path.Combine(ConfigurationManager.AppSettings["Resources"], empresa.RFC);
                                string pathCer = Path.Combine(path, "Certs", "csd.cer");
                                string pathKey = Path.Combine(path, "Certs", "csd.key");
                                string pass    = empresa.PassKey;
                                SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata2          = new SAT.CFDI.Cliente.Procesamiento.Encabezado(empresa.RFC, this.FechaHoy(), uuidsCancelar);
                                SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse ac2 = null;
                                acuse = this.EnviarCancelacionSAT(encLMetadata2, pathKey, pass, pathCer, ref ac2);
                                if (string.IsNullOrEmpty(acuse))
                                {
                                    acuse = "No se pudo conectar al servicio de cancelación del SAT";
                                }
                                int intEstatus2 = this.TraerEstatusSAT(uuid, ac2);
                                if (intEstatus2 != 201 && intEstatus2 != 202)
                                {
                                    Cancelador.Logger.Error(acuse);
                                    respuesta = intEstatus2 + " - " + Constantes.ErroresValidacion[intEstatus2];
                                    throw new FaultException(respuesta);
                                }
                                Cancelador.Logger.Info(acuse);
                                string directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"], ac2.RfcEmisor, ac2.Fecha.ToString("yyyyMMdd"));
                                if (!Directory.Exists(directorio))
                                {
                                    Directory.CreateDirectory(directorio);
                                }
                                string fileName = Path.Combine(directorio, "Cancelacion_" + uuid.ToString() + ".xml");
                                File.WriteAllText(fileName, acuse, Encoding.UTF8);
                                respuesta = intEstatus2 + " - " + Constantes.ErroresValidacion[intEstatus2];
                                result    = intEstatus2;
                                return(result);
                            }
                            else
                            {
                                timbre                  = new TimbreWs33();
                                timbre.RfcEmisor        = timbreHist.RfcEmisor;
                                timbre.RfcReceptor      = timbreHist.RfcReceptor;
                                timbre.AcuseCancelacion = timbreHist.AcuseCancelacion;
                                timbre.IdTimbre         = timbreHist.IdTimbre;
                                timbre.Uuid             = timbreHist.Uuid;
                                timbre.StrError         = "Hist";
                            }
                        }
                        if (timbre.RfcEmisor != empresa.RFC)
                        {
                            respuesta = "203 - UUID No corresponde el RFC del emisor y de quien solicita la cancelación.";
                            acuse     = "";
                            result    = 203;
                        }
                        else if (timbre.AcuseCancelacion != null)
                        {
                            respuesta = "202 - UUID Previamente cancelado";
                            acuse     = timbre.AcuseCancelacion;
                            result    = 202;
                        }
                        else
                        {
                            string path    = Path.Combine(ConfigurationManager.AppSettings["Resources"], empresa.RFC);
                            string pathCer = Path.Combine(path, "Certs", "csd.cer");
                            string pathKey = Path.Combine(path, "Certs", "csd.key");
                            string pass    = empresa.PassKey;
                            SAT.CFDI.Cliente.Procesamiento.Encabezado encLMetadata3          = new SAT.CFDI.Cliente.Procesamiento.Encabezado(empresa.RFC, this.FechaHoy(), uuidsCancelar);
                            SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse ac3 = null;
                            acuse = this.EnviarCancelacionSAT(encLMetadata3, pathKey, pass, pathCer, ref ac3);
                            if (string.IsNullOrEmpty(acuse))
                            {
                                acuse = "No se pudo conectar al servicio de cancelación del SAT";
                            }
                            int intEstatus3 = this.TraerEstatusSAT(uuid, ac3);
                            if (intEstatus3 != 201 && intEstatus3 != 202)
                            {
                                Cancelador.Logger.Error(acuse);
                                respuesta = intEstatus3 + " - " + Constantes.ErroresValidacion[intEstatus3];
                                throw new FaultException(respuesta);
                            }
                            Cancelador.Logger.Info(acuse);
                            timbre.Status = new int?(2);
                            string directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"], timbre.RfcEmisor, timbre.FechaFactura.ToString("yyyyMMdd"));
                            if (!Directory.Exists(directorio))
                            {
                                Directory.CreateDirectory(directorio);
                            }
                            string fileName = Path.Combine(directorio, "Cancelacion_" + timbre.Uuid.ToString() + ".xml");
                            File.WriteAllText(fileName, acuse, Encoding.UTF8);
                            tim.GuardarTimbre(timbre);
                            respuesta = intEstatus3 + " - " + Constantes.ErroresValidacion[intEstatus3];
                            result    = intEstatus3;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Cancelador.Logger.Error("(cancelar) Error: " + ex.Message + ((ex.InnerException == null) ? "" : ("\nExcepción Interna:" + ex.InnerException.Message)));
                throw;
            }
            return(result);
        }
        public bool EnvioSAT(TimbreWs33 topPComprobante)
        {
            try
            {
                GeneradorCadenasCfd gen = new GeneradorCadenasCfd();
                string     strLAcuseReciboSAT;
                byte[]     result;
                int        idErrorSAT;
                Encabezado encLMetadata;
                //SHA1 sha = new SHA1CryptoServiceProvider();
                string strComprobante = null;
                if (string.IsNullOrEmpty(topPComprobante.Xml))
                {
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Comprobante_" + topPComprobante.Uuid + ".xml");
                    strComprobante = File.ReadAllText(fileName, Encoding.UTF8);
                }
                else
                {
                    strComprobante = topPComprobante.Xml;
                }

                Comprobante comprobante = GeneradorCfdi.GetComprobanteFromString(strComprobante);
                //byte[] bytLCadenaOriginal = Encoding.UTF8.GetBytes(gen.CadenaOriginal(strComprobante));
                //result = sha.ComputeHash(bytLCadenaOriginal);
                string strLRfcEmisor = comprobante.Emisor.Rfc;
                //  string strLHash = topPComprobante.Hash;
                //  string version = comprobante.Version;
                string version = "3.3";

                //string strLCertificadoSAT = comprobante.Complemento.timbreFiscalDigital.NoCertificadoSAT;
                string strLCertificadoSAT = ConfigurationManager.AppSettings["NoCertificadoPac"];

                string   strLUUID          = comprobante.Complemento.timbreFiscalDigital.UUID;
                DateTime datLFechaTimbrado = comprobante.Complemento.timbreFiscalDigital.FechaTimbrado;
                string   strLPathArchivo   = AppDomain.CurrentDomain.BaseDirectory +
                                             ConfigurationManager.AppSettings["PathXMLTemporales"] + Guid.NewGuid() + ".xml";
                //Quitar addenda si tiene
                XElement xe      = XElement.Load(new StringReader(strComprobante));
                XElement addenda = xe.Elements(Constantes.CFDVersionNamespace + "Addenda").FirstOrDefault();

                if (addenda != null)
                {
                    addenda.Remove();
                }
                var tw = new SidetecStringWriter(Encoding.UTF8);
                xe.Save(tw, SaveOptions.DisableFormatting);
                string xml = tw.ToString();
                //escribimos el archivo en una carpeta para que el proceso de envio SAT lo tome//
                File.WriteAllText(strLPathArchivo, xml, Encoding.UTF8);
                //armamos el encabezado//
                encLMetadata = new Encabezado(strLRfcEmisor, version, strLCertificadoSAT, strLUUID, datLFechaTimbrado, strLPathArchivo);

                Log.Info("Enviando CFDI al SAT.");
                Log.Info("Se enviará el comprobante con el identificador: " + topPComprobante.IdTimbre);
                Log.Info("Encabezado." + encLMetadata.version + "|" + encLMetadata.UUID + "|" + encLMetadata.NumeroCertificado + "|" + encLMetadata.RfcEmisor + "|" + encLMetadata.Xml);

                var acuseReciboSAT = EnviarCFDIalSAT(encLMetadata);

                if (acuseReciboSAT != null)
                {
                    idErrorSAT = acuseReciboSAT.CodEstatus.Equals("Comprobante Rechazado",
                                                                  StringComparison.InvariantCultureIgnoreCase)
                                     ? Convert.ToInt32(acuseReciboSAT.Incidencia[0].CodigoError)
                                     : 0;
                    if (idErrorSAT != 501 || idErrorSAT != 502)
                    {
                    }
                    var acuseStream   = new MemoryStream();
                    var xmlSerializer = new XmlSerializer(typeof(SAT.CFDI.Cliente.Procesamiento.ServicioRecepcionCFDI.Acuse));
                    xmlSerializer.Serialize(acuseStream, acuseReciboSAT);
                    acuseStream.Seek(0, SeekOrigin.Begin);
                    var acuseReader = new StreamReader(acuseStream);
                    strLAcuseReciboSAT = acuseReader.ReadToEnd();
                    var directorio = Path.Combine(ConfigurationManager.AppSettings["RutaTimbrado"],
                                                  topPComprobante.RfcEmisor, topPComprobante.FechaFactura.ToString("yyyyMMdd"));
                    if (!Directory.Exists(directorio))
                    {
                        Directory.CreateDirectory(directorio);
                    }
                    var fileName = Path.Combine(directorio, "Acuse_" + topPComprobante.Uuid + ".xml");
                    File.WriteAllText(fileName, strLAcuseReciboSAT);
                }
                else
                {
                    idErrorSAT         = 103;
                    strLAcuseReciboSAT = "";
                }
                //idErrorSAT = TraerEstatusSAT(strLAcuseReciboSAT);

                Log.Info("Código de retorno SAT: " + idErrorSAT);
                GuardarInformacion(topPComprobante, idErrorSAT, strLAcuseReciboSAT, acuseReciboSAT);

                File.Delete(strLPathArchivo);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error al intentar enviar el CFD al SAT, Err:" + ex.ToString());
                return(false);
            }
        }
        public string CancelarBloqueCfdi(string directorioLog, string directorioAcuse, Encabezado encLMetadata, string strPPrivada, string pass, string strCertificado, ref SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse cAcuse)
        {
            string result;

            try
            {
                AccesoServicios.Logger.Info("Privada: " + strPPrivada);
                AccesoServicios.Logger.Info("Certificado: " + strCertificado);
                AccesoServicios.Logger.Info("rfc:" + encLMetadata.RfcEmisor);
                AccesoServicios.Logger.Info("fecha:" + encLMetadata.Fecha);
                AccesoServicios.Logger.Info("uuid:" + encLMetadata.LisMListaFolios[0].ToString());
                string strPXmlFirmado = "";
                if (File.Exists(strPPrivada + ".pem"))
                {
                    strPPrivada += ".pem";
                }
                string ext = Path.GetExtension(strPPrivada);
                AccesoServicios.SignXmlFile(this.ArmarXmlPreFirma(encLMetadata), ref strPXmlFirmado, OpensslKey.DecodePrivateKey(File.ReadAllBytes(strPPrivada), pass, ext));
                AccesoServicios.Logger.Info(strPXmlFirmado);
                SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.SignatureType a         = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.SignatureType();
                SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.ReferenceType reference = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.ReferenceType
                {
                    URI = ""
                };
                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                a.SignedInfo = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.SignedInfoType
                {
                    Reference = reference
                };
                string hex = strPXmlFirmado.Substring(strPXmlFirmado.IndexOf("<DigestValue>") + 13, strPXmlFirmado.IndexOf("</DigestValue>") - strPXmlFirmado.IndexOf("<DigestValue>") - 13);
                a.SignedInfo.Reference.DigestValue  = Convert.FromBase64String(hex);
                a.SignedInfo.Reference.DigestMethod = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.DigestMethodType
                {
                    Algorithm = "http://www.w3.org/2000/09/xmldsig#sha1"
                };
                a.SignedInfo.Reference.Transforms = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.TransformType[]
                {
                    new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.TransformType()
                };
                a.SignedInfo.Reference.Transforms[0].Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
                a.SignedInfo.CanonicalizationMethod            = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.CanonicalizationMethodType
                {
                    Algorithm = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
                };
                a.SignedInfo.SignatureMethod = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.SignatureMethodType
                {
                    Algorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
                };
                a.SignatureValue = Convert.FromBase64String(strPXmlFirmado.Substring(strPXmlFirmado.IndexOf("<SignatureValue>") + 16, strPXmlFirmado.IndexOf("</SignatureValue>") - strPXmlFirmado.IndexOf("<SignatureValue>") - 16));
                X509Certificate2 x509 = new X509Certificate2(strCertificado);
                a.KeyInfo          = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.KeyInfoType();
                a.KeyInfo.X509Data = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.X509DataType();
                a.KeyInfo.X509Data.X509IssuerSerial = new SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.X509IssuerSerialType();
                a.KeyInfo.X509Data.X509IssuerSerial.X509IssuerName   = x509.IssuerName.Name.ToString();
                a.KeyInfo.X509Data.X509IssuerSerial.X509SerialNumber = x509.SerialNumber;
                a.KeyInfo.X509Data.X509Certificate = File.ReadAllBytes(strCertificado);
                Console.WriteLine("Enviando Cancelación...");
                string      a2 = a.ToString();
                Cancelacion mensajeCancelacion = new Cancelacion
                {
                    RfcEmisor = encLMetadata.RfcEmisor,
                    Fecha     = Convert.ToDateTime(encLMetadata.Fecha),
                    Signature = a
                };
                mensajeCancelacion.Folios = new CancelacionFolios[encLMetadata.LisMListaFolios.Count];
                for (int i = 0; i < encLMetadata.LisMListaFolios.Count; i++)
                {
                    mensajeCancelacion.Folios[i] = new CancelacionFolios
                    {
                        UUID = encLMetadata.LisMListaFolios[i].ToString()
                    };
                }
                if (mensajeCancelacion.Folios.Count <CancelacionFolios>() > 0)
                {
                    Console.WriteLine("Autenticando...");
                    HttpRequestMessageProperty tokenAutenticacion = this.AutenticaServicio();
                    using (new OperationContextScope(this.ClienteCancelacion.InnerChannel))
                    {
                        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = tokenAutenticacion;
                        Console.WriteLine("Cancelando...");
                        SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse acuseCancelacion = this.ClienteCancelacion.CancelaCFD(mensajeCancelacion);
                        MemoryStream  acuseStream   = new MemoryStream();
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(SAT.CFDI.Cliente.Procesamiento.ServicioCancelacionCFDI.Acuse));
                        xmlSerializer.Serialize(acuseStream, acuseCancelacion);
                        acuseStream.Seek(0L, SeekOrigin.Begin);
                        StreamReader acuseReader = new StreamReader(acuseStream);
                        AccesoServicios.Log.Info("Terminando el proceso...");
                        cAcuse = acuseCancelacion;
                        result = acuseReader.ReadToEnd();
                        return(result);
                    }
                }
                result = string.Empty;
                return(result);
            }
            catch (Exception exception)
            {
                AccesoServicios.Log.Error("(CancelarBloqueCfdi) Error al cancelar los CFDI's " + exception.ToString());
            }
            result = "";
            return(result);
        }
 public SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType Asignature(string strPPrivada, Encabezado encLMetadata, string pass, string strCertificado)
 {
     SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType result;
     try
     {
         string strPXmlFirmado = "";
         SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType Asig = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureType();
         Asig.Id            = "Signature";
         Asig.SignedInfo    = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignedInfoType();
         Asig.SignedInfo.Id = "Signature-SignedInfo";
         Asig.SignedInfo.CanonicalizationMethod           = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.CanonicalizationMethodType();
         Asig.SignedInfo.CanonicalizationMethod.Algorithm = "http://www.w3.org/TR/2001/REC-xml-c14n20010315";
         Asig.SignedInfo.SignatureMethod           = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.SignatureMethodType();
         Asig.SignedInfo.SignatureMethod.Algorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
         Asig.SignedInfo.Reference     = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.ReferenceType();
         Asig.SignedInfo.Reference.URI = "#Certificate1";
         List <SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.TransformType> T = new List <SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.TransformType>();
         T.Add(new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.TransformType
         {
             Algorithm = "http://www.w3.org/2000/09/xmldsig#envelopedsignature"
         });
         Asig.SignedInfo.Reference.Transforms             = T.ToArray();
         Asig.SignedInfo.Reference.DigestMethod           = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.DigestMethodType();
         Asig.SignedInfo.Reference.DigestMethod.Algorithm = "http://www.w3.org/2000/09/xmldsig#sha1";
         if (File.Exists(strPPrivada + ".pem"))
         {
             strPPrivada += ".pem";
         }
         string ext = Path.GetExtension(strPPrivada);
         AccesoServicios.SignXmlFile(this.ArmarXmlPreFirma(encLMetadata), ref strPXmlFirmado, OpensslKey.DecodePrivateKey(File.ReadAllBytes(strPPrivada), pass, ext));
         string hex = strPXmlFirmado.Substring(strPXmlFirmado.IndexOf("<DigestValue>") + 13, strPXmlFirmado.IndexOf("</DigestValue>") - strPXmlFirmado.IndexOf("<DigestValue>") - 13);
         Asig.SignedInfo.Reference.DigestValue = Convert.FromBase64String(hex);
         Asig.SignatureValue = Convert.FromBase64String(strPXmlFirmado.Substring(strPXmlFirmado.IndexOf("<SignatureValue>") + 16, strPXmlFirmado.IndexOf("</SignatureValue>") - strPXmlFirmado.IndexOf("<SignatureValue>") - 16));
         X509Certificate2 x509 = new X509Certificate2(strCertificado);
         Asig.KeyInfo          = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.KeyInfoType();
         Asig.KeyInfo.X509Data = new SAT.CFDI.Cliente.Procesamiento.ServicioRelacionados.X509DataType();
         Asig.KeyInfo.X509Data.X509Certificate = File.ReadAllBytes(strCertificado);
         Asig.KeyInfo.Id = "Certificate1";
         result          = Asig;
     }
     catch (Exception exception)
     {
         AccesoServicios.Log.Error("(Asignature) Error al generar la firma de los CFDI's " + exception.ToString());
         result = null;
     }
     return(result);
 }
        public SAT.CFDI.Cliente.Procesamiento.ServicioRecepcionCFDI.Acuse EnviarBloqueCfdi(Encabezado encPMEtadato)
        {
            Stream contenidoArchivo = null;

            SAT.CFDI.Cliente.Procesamiento.ServicioRecepcionCFDI.Acuse result;
            try
            {
                EncabezadoCFDI encabezadoCfdi = new EncabezadoCFDI
                {
                    RfcEmisor          = encPMEtadato.RfcEmisor,
                    VersionComprobante = encPMEtadato.version,
                    NumeroCertificado  = encPMEtadato.NumeroCertificado,
                    UUID  = encPMEtadato.UUID,
                    Fecha = encPMEtadato.Fecha
                };
                AccesoServicios.Log.Info("Autenticacion");
                HttpRequestMessageProperty tokenAutenticacion = this.AutenticaServicio();
                AccesoServicios.Log.Info("Termina Autenticacion");
                using (new OperationContextScope(this.ClienteRecepcion.InnerChannel))
                {
                    try
                    {
                        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = tokenAutenticacion;
                        contenidoArchivo = AccesoDisco.RecuperaArchivo(encPMEtadato.Xml);
                        AdministradorLogs.RegistraEntrada(string.Format("Se inicia envío de archivo, Tamaño: {0} bytes", contenidoArchivo.Length));
                        AccesoServicios.Log.Info("Inicia AlmacenarCfdiFramework4");
                        string rutaBlob = this.ClienteAlmacenBlob.AlmacenarCfdiFramework4(contenidoArchivo, File.ReadAllText(encPMEtadato.Xml), Path.GetFileName(encPMEtadato.Xml));
                        AccesoServicios.Log.Info("Termina AlmacenarCfdiFramework4");
                        AccesoServicios.Log.Info("Inicia Recibe");
                        SAT.CFDI.Cliente.Procesamiento.ServicioRecepcionCFDI.Acuse acuseRecepcion = this.ClienteRecepcion.Recibe(encabezadoCfdi, rutaBlob);
                        contenidoArchivo.Close();
                        AccesoServicios.Log.Info("Termina Recibe");
                        result = acuseRecepcion;
                        return(result);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.ToString());
                        if (contenidoArchivo != null && contenidoArchivo.CanRead)
                        {
                            contenidoArchivo.Close();
                        }
                        AccesoServicios.Log.Error(string.Format("Se genero un error proceso de recepción: {0}\n\n Stack Trace: {1}", exception.Message, exception.StackTrace));
                    }
                }
            }
            catch (Exception exception)
            {
                if (contenidoArchivo != null && contenidoArchivo.CanRead)
                {
                    contenidoArchivo.Close();
                }
                AccesoServicios.Log.Error(string.Format("Se genero un error proceso de recepción: {0}\n\n Stack Trace: {1}", exception.Message, exception.StackTrace));
            }
            result = null;
            return(result);
        }