private ServicioLocal.Business.Complemento.Pagos DesSerializarPagos(XElement element)
        {
            IEnumerable <XElement> ImpL = element.Elements(this._ns + "Complemento");

            ServicioLocal.Business.Complemento.Pagos result;
            if (ImpL != null)
            {
                IEnumerable <XElement> pag = ImpL.Elements(this._ns7 + "Pagos");
                using (IEnumerator <XElement> enumerator = pag.GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        XElement      e      = enumerator.Current;
                        XmlSerializer ser    = new XmlSerializer(typeof(ServicioLocal.Business.Complemento.Pagos));
                        string        xml    = e.ToString();
                        StringReader  reader = new StringReader(xml);
                        ServicioLocal.Business.Complemento.Pagos comLXMLComprobante = (ServicioLocal.Business.Complemento.Pagos)ser.Deserialize(reader);
                        result = comLXMLComprobante;
                        return(result);
                    }
                }
                result = null;
            }
            else
            {
                result = null;
            }
            return(result);
        }
        public TimbradoResponse TimbraCfdiMovil(string userName, string password, string comprobante)
        {
            TimbradoResponse result2;

            try
            {
                string erroresNomina = "0";
                ServicioTimbradoMovil.Logger.Debug(userName);
                MembershipUser x = NtLinkLogin.ValidateUser(userName, password);
                if (x == null)
                {
                    throw new FaultException("Nombre de usuario o contraseña incorrecta");
                }
                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<ine:INE "))
                {
                    string     erroINE = "";
                    INE        I       = this.DesSerializarINE(element, ref erroINE);
                    ValidarINE VI      = new ValidarINE();
                    erroINE = VI.ProcesarINE(I);
                    if (erroINE != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroINE
                        };
                        return(result2);
                    }
                }
                if (comprobante.Contains("<ecc11:EstadoDeCuentaCombustible"))
                {
                    string erroECC = "";
                    EstadoDeCuentaCombustible E = this.DesSerializarECC(element, ref erroECC);
                    ValidarECC VE = new ValidarECC();
                    erroECC = VE.ProcesarECC(E, comp.TipoDeComprobante, comp.Version);
                    if (erroECC != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroECC
                        };
                        return(result2);
                    }
                }
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = ErrorPagos
                        };
                        return(result2);
                    }
                }
                NtLinkClientes nlc     = new NtLinkClientes();
                clientes       cliente = nlc.GetCliente(comp.Receptor.Rfc);
                bool           nomin12 = comprobante.Contains("nomina12:Nomina");
                List <Nomina>  nom     = new List <Nomina>();

                if (nomin12)
                {
                    string erroresNom = null;
                    var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                    nom.Add(nomx);
                    if (erroresNom != null)
                    {
                        result2 = new TimbradoResponse
                        {
                            Valido           = false,
                            DescripcionError = erroresNom
                        };
                        return(result2);
                    }
                }
                bool ComerExt = comprobante.Contains("cce11:ComercioExterior");
                if (comp.Emisor != null && comp.Emisor.Rfc != null)
                {
                    empresa empresa = new empresa();
                    if (!TimbradoUtils.EmpresaMultipleRFC(comp.Emisor.Rfc))
                    {
                        empresa = TimbradoUtils.ValidarUsuario(comp.Emisor.Rfc);
                    }
                    else
                    {
                        empresa = NtLinkUsuarios.GetEmpresaByUserId(x.ProviderUserKey.ToString());
                        empresa = TimbradoUtils.ValidarUsuarioMultiple(empresa);
                    }
                    if (empresa == null)
                    {
                        result2 = null;
                    }
                    else
                    {
                        string result = null;
                        TimbreFiscalDigital timbre = null;
                        string acuseSat            = "";
                        string hash = null;
                        if (ComerExt && erroresNomina == "0")
                        {
                            string erroresComer           = null;
                            ValidarComercioExterior val   = new ValidarComercioExterior();
                            ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                            if (erroresComer != null)
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = erroresComer
                                };
                                return(result2);
                            }
                            erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                        }
                        if (nomin12 && erroresNomina == "0")
                        {
                            erroresNomina = this._val.ProcesarNomina(nom, comp);
                        }
                        if (erroresNomina == "0")
                        {
                            try
                            {
                                string           path      = Path.Combine(ConfigurationManager.AppSettings["Resources"], empresa.RFC, "Certs");
                                X509Certificate2 cert      = new X509Certificate2(Path.Combine(path, "csd.cer"));
                                string           rutaLlave = Path.Combine(path, "csd.key");
                                if (File.Exists(rutaLlave + ".pem"))
                                {
                                    rutaLlave += ".pem";
                                }
                                ServicioTimbradoMovil.Logger.Debug("Ruta Llave " + rutaLlave);
                                if (!File.Exists(rutaLlave))
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error certificado de la empresa no está cargado en el sistema"
                                    };
                                    return(result2);
                                }
                                GeneradorCfdi gen     = new GeneradorCfdi();
                                string        sellado = gen.GenerarCfdSinTimbre(comp, cert, rutaLlave, empresa.PassKey, comprobante);
                                if (sellado == null)
                                {
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al sellar el comprobante: al sellar"
                                    };
                                    return(result2);
                                }
                                comprobante = sellado;
                            }
                            catch (FaultException ex)
                            {
                                ServicioTimbradoMovil.Logger.Error(ex);
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = ex.Message
                                };
                                return(result2);
                            }
                            ValidarCFDI33 valida      = new ValidarCFDI33();
                            string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                            if (errorCFDI33 != "0")
                            {
                                result2 = new TimbradoResponse
                                {
                                    Valido           = false,
                                    DescripcionError = errorCFDI33
                                };
                            }
                            else
                            {
                                Dictionary <int, string> dict = this._val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                                {
                                    if (!string.IsNullOrEmpty(comp.Confirmacion))
                                    {
                                        using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                                        {
                                            ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                                            C.procesado = new bool?(true);
                                            db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                                            db.SaveChanges();
                                        }
                                    }
                                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                                    {
                                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                                    }
                                    string cfdiTimbrado = result;
                                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                                    {
                                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empresa, true, false))
                                        {
                                            throw new Exception("Error al abrir el comprobante");
                                        }
                                        NtLinkFactura fac = new NtLinkFactura(0);
                                        if (string.IsNullOrEmpty(empresa.RegimenFiscal))
                                        {
                                            throw new FaultException("Debes capturar el regimen fiscal de la empresa");
                                        }
                                        fac.Emisor      = empresa;
                                        fac.Receptor    = cliente;
                                        fac.Factura     = this.CrearFactura(comp, empresa.IdEmpresa, cliente.idCliente);
                                        fac.Factura.Uid = timbre.UUID;
                                        fac.Save();
                                        comp.Complemento = new ComprobanteComplemento();
                                        comp.Complemento.timbreFiscalDigital = timbre;
                                        comp.XmlString            = cfdiTimbrado;
                                        comp.CadenaOriginalTimbre = timbre.cadenaOriginal;
                                        string saldo = comp.Total.ToString(CultureInfo.InvariantCulture);
                                        comp.CantidadLetra = CantidadLetra.Enletras(saldo.ToString(), comp.Moneda);
                                        comp.Regimen       = empresa.RegimenFiscal;
                                        if (comp.TipoDeComprobante.ToString() == "ingreso")
                                        {
                                            comp.Titulo = "Factura";
                                        }
                                        else if (comp.TipoDeComprobante.ToString() == "egreso")
                                        {
                                            comp.Titulo = "Nota de Crédito";
                                        }
                                        string ruta = Path.Combine(ConfigurationManager.AppSettings["Salida"], empresa.RFC);
                                        if (!Directory.Exists(ruta))
                                        {
                                            Directory.CreateDirectory(ruta);
                                        }
                                        string xmlFile = Path.Combine(ruta, timbre.UUID + ".xml");
                                        ServicioTimbradoMovil.Logger.Debug(comp.XmlString);
                                        StreamWriter sw = new StreamWriter(xmlFile, false, Encoding.UTF8);
                                        sw.Write(comp.XmlString);
                                        sw.Close();
                                        byte[] pdf = new byte[0];
                                        try
                                        {
                                            long          id  = 0L;
                                            GeneradorCfdi gen = new GeneradorCfdi();
                                            pdf = gen.GetPdfFromComprobante(comp, empresa.Orientacion, fac.Factura.TipoDocumento, ref id, fac.Factura.Metodo);
                                            string pdfFile = Path.Combine(ruta, timbre.UUID + ".pdf");
                                            File.WriteAllBytes(pdfFile, pdf);
                                        }
                                        catch (Exception ee)
                                        {
                                            ServicioTimbradoMovil.Logger.Error(ee);
                                            if (ee.InnerException != null)
                                            {
                                                ServicioTimbradoMovil.Logger.Error(ee.InnerException);
                                            }
                                        }
                                    }
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = cfdiTimbrado
                                    };
                                }
                                else if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                                {
                                    string totalLetra = comp.Total.ToString(CultureInfo.InvariantCulture);
                                    string enteros;
                                    string decimales;
                                    if (totalLetra.IndexOf('.') == -1)
                                    {
                                        enteros   = "0";
                                        decimales = "0";
                                    }
                                    else
                                    {
                                        enteros   = totalLetra.Substring(0, totalLetra.IndexOf('.'));
                                        decimales = totalLetra.Substring(totalLetra.IndexOf('.') + 1);
                                    }
                                    string total        = enteros.PadLeft(18, '0') + "." + decimales.PadRight(6, '0');
                                    int    tam_var      = comp.Sello.Length;
                                    string Var_Sub      = comp.Sello.Substring(tam_var - 8, 8);
                                    string URL          = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx";
                                    string cadenaCodigo = string.Concat(new string[]
                                    {
                                        URL,
                                        "?&id=",
                                        timbre.UUID,
                                        "&fe=",
                                        Var_Sub,
                                        "&re=",
                                        comp.Emisor.Rfc,
                                        "&rr=",
                                        comp.Receptor.Rfc,
                                        "&tt=",
                                        total
                                    });
                                    string qr = this.GetQrCode(cadenaCodigo);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido       = true,
                                        QrCodeBase64 = qr,
                                        CadenaTimbre = timbre.cadenaOriginal,
                                        Cfdi         = result
                                    };
                                }
                                else if (dict.Count > 0)
                                {
                                    StringBuilder res = new StringBuilder();
                                    foreach (KeyValuePair <int, string> d in dict)
                                    {
                                        res.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                                    }
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = res.ToString()
                                    };
                                }
                                else
                                {
                                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                                    result2 = new TimbradoResponse
                                    {
                                        Valido           = false,
                                        DescripcionError = "Error al abrir el comprobante"
                                    };
                                }
                            }
                        }
                        else
                        {
                            ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante: " + erroresNomina);
                            result2 = new TimbradoResponse
                            {
                                Valido           = false,
                                DescripcionError = erroresNomina
                            };
                        }
                    }
                }
                else
                {
                    ServicioTimbradoMovil.Logger.Error("Error al abrir el comprobante:" + comprobante);
                    result2 = new TimbradoResponse
                    {
                        Valido           = false,
                        DescripcionError = "Error al abrir el comprobante"
                    };
                }
            }
            catch (FaultException ex)
            {
                ServicioTimbradoMovil.Logger.Error(ex);
                result2 = new TimbradoResponse
                {
                    Valido           = false,
                    DescripcionError = ex.Message
                };
            }
            catch (Exception ex2)
            {
                ServicioTimbradoMovil.Logger.Error(ex2);
                throw new FaultException("Error al abrir el comprobante");
            }
            return(result2);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Timbra un comprobante
        /// </summary>
        /// <param name="comprobante">Documento para validar y timbrar</param>
        /// <returns>Una cadena con el timbre fiscal digital (TFD)</returns>
        public string TimbraCfdi(string comprobante, string userName, string password, string LLave, string aplicacion)
        {
            string result2;

            try
            {
                if (string.IsNullOrEmpty(userName))
                {
                    return("Nombre de usuario o contraseña incorrecta");
                }
                CertificadorService.Logger.Debug(userName);
                if (aplicacion == "CON")
                {
                    var Licencia = ValidarLicencia(LLave);
                    if (Licencia == false)
                    {
                        return("Licencia no valida");
                    }
                }
                MembershipUser x = NtLinkLogin.ValidateUser(userName, password);
                if (x == null)
                {
                    throw new FaultException("Nombre de usuario o contraseña incorrecta");
                }


                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                empresa empres = new empresa();
                if (comp.Emisor != null && comp.Emisor.Rfc != null)
                {
                    string vemp = ValidarUsuario(comp.Emisor.Rfc, x, ref empres);
                    if (vemp != "OK")
                    {
                        return(vemp);
                    }
                }
                else
                {
                    return("Error: Los datos del emisor incompletos");
                }
                //-------------------------

                if (comprobante.Contains("<ieeh:IngresosHidrocarburos"))
                {
                    string erroIH = "";
                    IngresosHidrocarburos       I  = this.DesSerializarIH(element, ref erroIH);
                    ValidarIngresoHidrocarburos VI = new ValidarIngresoHidrocarburos();
                    erroIH = VI.ProcesarIngresoHidrocarburos(I, comp.Version, comp.TipoDeComprobante, comp.Total);
                    if (erroIH != "0")
                    {
                        result2 = erroIH;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<gceh:GastosHidrocarburos"))
                {
                    string erroGH = "";
                    GastosHidrocarburos        I2  = this.DesSerializarGH(element, ref erroGH);
                    ValidarGastosHidrocarburos VI2 = new ValidarGastosHidrocarburos();
                    erroGH = VI2.ProcesarGastosHidrocarburos(I2, comp.Version, comp.TipoDeComprobante);
                    if (erroGH != "0")
                    {
                        result2 = erroGH;
                        return(result2);
                    }
                }
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (comp.TipoDeComprobante == "P" && !pago10)
                {
                    result2 = "CFDI no contiene el complemento PAGO";
                    return(result2);
                }
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = ErrorPagos;
                        return(result2);
                    }
                }
                bool          ComerExt    = comprobante.Contains("cce11:ComercioExterior");
                ValidarCFDI33 valida      = new ValidarCFDI33();
                string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                if (errorCFDI33 != "0")
                {
                    CertificadorService.Logger.Error("Error al abrir el comprobante: " + errorCFDI33);
                    return(errorCFDI33);
                }
                bool          nomin12 = comprobante.Contains("nomina12:Nomina");
                List <Nomina> nom     = new List <Nomina>();
                if (nomin12)
                {
                    string erroresNom = null;
                    var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                    nom.Add(nomx);
                    if (erroresNom != null)
                    {
                        result2 = erroresNom;
                        return(result2);
                    }
                }

                NtLinkSistema       nls           = new NtLinkSistema();
                string              result        = null;
                TimbreFiscalDigital timbre        = null;
                string              acuseSat      = "";
                string              hash          = null;
                string              erroresNomina = "0";
                if (ComerExt && erroresNomina == "0")
                {
                    string erroresComer           = null;
                    ValidarComercioExterior val   = new ValidarComercioExterior();
                    ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                    if (erroresComer != null)
                    {
                        result2 = erroresComer;
                        return(result2);
                    }
                    erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                }
                if (nomin12 && erroresNomina == "0")
                {
                    erroresNomina = this.val.ProcesarNomina(nom, comp);
                    if (erroresNomina != "0")
                    {
                        return(erroresNomina);
                    }
                }

                Dictionary <int, string> dict = this.val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                {
                    SerializadorTimbres sert = new SerializadorTimbres();
                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                    {
                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                    }
                    string res          = sert.GetTimbreXml(timbre);
                    string cfdiTimbrado = result;
                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                    {
                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empres, true, false))
                        {
                            throw new Exception("Error al abrir el comprobante");
                        }
                    }
                    result2 = res;
                }
                else
                {
                    if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                    {
                        XElement el          = XElement.Parse(result);
                        XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                        if (complemento != null)
                        {
                            XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                            if (t != null)
                            {
                                SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                                t.Save(sw, SaveOptions.DisableFormatting);
                                result2 = sw.ToString();
                                return(result2);
                            }
                        }
                    }
                    if (dict.Count > 0)
                    {
                        StringBuilder res2 = new StringBuilder();
                        foreach (KeyValuePair <int, string> d in dict)
                        {
                            res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                        }
                        result2 = res2.ToString();
                    }
                    else
                    {
                        CertificadorService.Logger.Error("Error al abrir el comprobante: " + comprobante);
                        result2 = "Error al abrir el comprobante";
                    }
                }
            }
            catch (Exception ex)
            {
                CertificadorService.Logger.Error(ex);
                result2 = "Error al abrir el comprobante: " + ex.Message;
            }
            return(result2);
        }
Exemplo n.º 4
0
        //---------------------------------------------------------------------------------------------
        public string ProcesarPago(Comprobante com, ServicioLocal.Business.Complemento.Pagos Pag, Pagoo.Comprobante c)
        {
            string result;

            if (com.TipoDeComprobante != "P")
            {
                result = "CRP101 - El valor del campo TipoDeComprobante debe ser \"P\"";
            }
            else if (c.SubTotal != "0")
            {
                result = "CRP102 - El valor del campo SubTotal debe ser cero \"0\".";
            }
            else if (com.Moneda != "XXX")
            {
                result = "CRP103 - El valor del campo Moneda debe ser \"XXX\".";
            }
            else if (com.FormaPagoSpecified)
            {
                result = "CRP104 - El campo FormaPago no se debe registrar en el CFDI.";
            }
            else if (com.MetodoPagoSpecified)
            {
                result = "CRP105 - El campo MetodoPago no se debe registrar en el CFDI.";
            }
            else if (!string.IsNullOrEmpty(com.CondicionesDePago))
            {
                result = "CRP106 - El campo CondicionesDePago no se debe registrar en el CFDI.";
            }
            else if (com.DescuentoSpecified)
            {
                result = "CRP107 - El campo Descuento no se debe registrar en el CFDI.";
            }
            else if (com.TipoCambioSpecified)
            {
                result = "CRP108 - El campo TipoCambio no se debe registrar en el CFDI.";
            }
            else if (c.Total != "0")
            {
                result = "CRP109 - El valor del campo Total debe ser cero \"0\".";
            }
            else if (com.Receptor != null && com.Receptor.UsoCFDI != "P01")
            {
                result = "CRP110 - El valor del campo UsoCFDI debe ser \"P01\".";
            }
            else
            {
                if (com.Conceptos != null)
                {
                    if (com.Conceptos.Count <ComprobanteConcepto>() != 1)
                    {
                        result = "CRP111 - Solo debe existir un Concepto en el CFDI. ";
                        return(result);
                    }
                    foreach (ComprobanteConcepto conp in com.Conceptos)
                    {
                        if (conp.Impuestos != null)
                        {
                            result = "CRP112 - No se deben registrar apartados dentro de Conceptos";
                            return(result);
                        }
                        if (conp.ComplementoConcepto != null)
                        {
                            result = "CRP112 - No se deben registrar apartados dentro de Conceptos";
                            return(result);
                        }
                        if (conp.CuentaPredial != null)
                        {
                            result = "CRP112 - No se deben registrar apartados dentro de Conceptos";
                            return(result);
                        }
                        if (conp.InformacionAduanera != null)
                        {
                            result = "CRP112 - No se deben registrar apartados dentro de Conceptos";
                            return(result);
                        }
                        if (conp.Parte != null)
                        {
                            result = "CRP112 - No se deben registrar apartados dentro de Conceptos";
                            return(result);
                        }
                        if (conp.ClaveProdServ != "84111506")
                        {
                            result = "CRP113 - El valor del campo ClaveProdServ debe ser \"84111506\".";
                            return(result);
                        }
                        if (!string.IsNullOrEmpty(conp.NoIdentificacion))
                        {
                            result = "CRP114 - El campo NoIdentificacion no se debe registrar en el CFDI.";
                            return(result);
                        }
                        if (conp.Cantidad != 1m)
                        {
                            result = "CRP115 - El valor del campo Cantidad debe ser \"1\".";
                            return(result);
                        }
                        if (conp.ClaveUnidad != "ACT")
                        {
                            result = "CRP116 - El valor del campo ClaveUnidad debe ser \"ACT\".";
                            return(result);
                        }
                        if (!string.IsNullOrEmpty(conp.Unidad))
                        {
                            result = "CRP117 - El campo Unidad no se debe registrar en el CFDI.";
                            return(result);
                        }
                        if (conp.Descripcion != "Pago")
                        {
                            result = "CRP118 - El valor del campo Descripcion debe ser \"Pago\".";
                            return(result);
                        }
                        if (conp.ValorUnitario != 0m)
                        {
                            result = "CRP119 - El valor del campo ValorUnitario debe ser cero \"0\".";
                            return(result);
                        }
                        if (conp.Importe != 0m)
                        {
                            result = "CRP120 - El valor del campo Importe debe ser cero \"0\".";
                            return(result);
                        }
                        if (conp.DescuentoSpecified)
                        {
                            result = "CRP121 - El campo Descuento no se debe registrar en el CFDI.";
                            return(result);
                        }
                    }
                    foreach (Pagoo.ComprobanteConcepto conp2 in c.Conceptos)
                    {
                        if (conp2.ValorUnitario != "0")
                        {
                            result = "CRP119 - El valor del campo ValorUnitario debe ser cero \"0\".";
                            return(result);
                        }
                        if (conp2.Importe != "0")
                        {
                            result = "CRP120 - El valor del campo Importe debe ser cero \"0\".";
                            return(result);
                        }
                        if (conp2.Cantidad != "1")
                        {
                            result = "CRP115 - El valor del campo Cantidad debe ser \"1\".";
                            return(result);
                        }
                    }
                }
                if (com.Impuestos != null)
                {
                    result = "CRP122 - No se debe registrar el apartado de Impuestos en el CFDI.";
                }
                else
                {
                    foreach (PagosPago pagos in Pag.Pago)
                    {
                        if (pagos.FormaDePagoP == "99")
                        {
                            result = "CRP201 - El valor del campo FormaDePagoP debe ser distinto de \"99\".";
                            return(result);
                        }
                        if (pagos.MonedaP == "XXX")
                        {
                            result = "CRP202 - El campo MonedaP debe ser distinto de \"XXX\"";
                            return(result);
                        }
                        if (pagos.MonedaP != "MXN")
                        {
                            if (!pagos.TipoCambioPSpecified)
                            {
                                result = "CRP203 - El campo TipoCambioP se debe registrar.";
                                return(result);
                            }
                        }
                        else if (pagos.TipoCambioPSpecified)
                        {
                            result = "CRP204 - El campo TipoCambioP no se debe registrar.";
                            return(result);
                        }
                        OperacionesCatalogos  o9   = new OperacionesCatalogos();
                        CatalogosSAT.c_Moneda mone = o9.Consultar_Moneda(pagos.MonedaP);
                        if (mone != null)
                        {
                            string varia             = mone.Variacion;
                            OperacionesCatalogos o10 = new OperacionesCatalogos();
                            Divisas divisa           = o10.Consultar_TipoDivisa(pagos.MonedaP);
                            if (divisa != null)
                            {
                                decimal inferior = this.CalculoInferiorPorcentajeMoneda(divisa.PesosDivisa, (int)Convert.ToInt16(varia));
                                decimal superior = this.CalculoSuperiorPorcentajeMoneda(divisa.PesosDivisa, (int)Convert.ToInt16(varia));
                                if (pagos.TipoCambioP < inferior)
                                {
                                    if (string.IsNullOrEmpty(com.Confirmacion))
                                    {
                                        result = "CRP205 - Cuando el valor del campo TipoCambio se encuentre fuera de los límites establecidos, debe existir el campo Confirmacion.";
                                        return(result);
                                    }
                                }
                                if (pagos.TipoCambioP > superior)
                                {
                                    if (string.IsNullOrEmpty(com.Confirmacion))
                                    {
                                        result = "CRP205 - Cuando el valor del campo TipoCambioP se encuentre fuera de los límites establecidos, debe existir el campo Confirmacion";
                                        return(result);
                                    }
                                }
                            }
                        }
                        decimal tot = 0m;
                        if (pagos.DoctoRelacionado == null)
                        {
                            result = "CRP000 - El numero de elementos DoctoRelacionado debe ser mayor a cero";
                            return(result);
                        }
                        if (pagos.DoctoRelacionado.Count <PagosPagoDoctoRelacionado>() == 0)
                        {
                            result = "CRP000 - El numero de elementos DoctoRelacionado debe ser mayor a cero";
                            return(result);
                        }
                        PagosPagoDoctoRelacionado[] doctoRelacionado = pagos.DoctoRelacionado;
                        for (int i = 0; i < doctoRelacionado.Length; i++)
                        {
                            PagosPagoDoctoRelacionado doc = doctoRelacionado[i];
                            if (doc.ImpPagadoSpecified)
                            {
                                tot += doc.ImpPagado;
                            }
                        }
                        if (pagos.Monto <= 0m)
                        {
                            result = "CRP207 - El valor del campo Monto no es mayor que cero \"0\".";
                            return(result);
                        }
                        decimal MontoDocumentos = pagos.Monto;
                        if (pagos.MonedaP != "MXN")
                        {
                            MontoDocumentos *= pagos.TipoCambioP;
                            MontoDocumentos  = decimal.Round(MontoDocumentos, mone.Decimales.Value, MidpointRounding.AwayFromZero);
                        }
                        if (tot > MontoDocumentos)
                        {
                            result = "CRP206 - La suma de los valores registrados en el campo ImpPagado de los apartados DoctoRelacionado no es menor o igual que el valor del campo Monto.";
                            return(result);
                        }
                        string mon = pagos.Monto.ToString();
                        if (mon != null)
                        {
                            if (mon != "0")
                            {
                                string[] split = mon.Split(".".ToCharArray());
                                if (split.Count <string>() <= 1)
                                {
                                    result = "CRP208 - El valor del campo Monto debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaP.";
                                    return(result);
                                }
                                if (split[1].Count <char>() != (int)Convert.ToInt16(mone.Decimales))
                                {
                                    result = "CRP208 - El valor del campo Monto debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaP.";
                                    return(result);
                                }
                            }
                        }
                        OperacionesCatalogos             o11 = new OperacionesCatalogos();
                        CatalogosSAT.c_TipoDeComprobante TCP = o11.Consultar_TipoDeComprobante(com.TipoDeComprobante);
                        if (TCP != null)
                        {
                            decimal monto        = pagos.Monto;
                            long?   valor_máximo = TCP.Valor_máximo;
                            if (monto > valor_máximo.GetValueOrDefault() && valor_máximo.HasValue)
                            {
                                if (string.IsNullOrEmpty(com.Confirmacion))
                                {
                                    result = "CRP209 - Cuando el valor del campo Monto se encuentre fuera de los límites establecidos, debe existir el campo Confirmacion";
                                    return(result);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(pagos.RfcEmisorCtaOrd))
                        {
                            if (pagos.RfcEmisorCtaOrd != "XEXX010101000")
                            {
                                Operaciones_IRFC r = new Operaciones_IRFC();
                                vI_RFC           t = r.Consultar_IRFC(pagos.RfcEmisorCtaOrd);
                                if (t == null)
                                {
                                    result = "CRP210 - El RFC del campo RfcEmisorCtaOrd no se encuentra en la lista de RFC.";
                                    return(result);
                                }
                            }
                            else if (string.IsNullOrEmpty(pagos.NomBancoOrdExt))
                            {
                                result = "CRP211 - El campo NomBancoOrdExt se debe registrar.";
                                return(result);
                            }
                        }
                        if (pagos.FormaDePagoP != "02" && pagos.FormaDePagoP != "03" && pagos.FormaDePagoP != "04" && pagos.FormaDePagoP != "05" && pagos.FormaDePagoP != "06" && pagos.FormaDePagoP != "28" && pagos.FormaDePagoP != "29" && !string.IsNullOrEmpty(pagos.CtaOrdenante))
                        {
                            result = "CRP212 - El campo CtaOrdenante no se debe registrar.";
                            return(result);
                        }
                        if (!string.IsNullOrEmpty(pagos.CtaOrdenante))
                        {
                            OperacionesCatalogos     o10       = new OperacionesCatalogos();
                            CatalogosSAT.c_FormaPago formaPago = o10.Consultar_FormaPago(pagos.FormaDePagoP);
                            if (formaPago.PatroncuentaBeneficiaria != "No" && formaPago.PatroncuentaBeneficiaria != "Opcional")
                            {
                                if (!this.validarExpresion(formaPago.PatroncuentaBeneficiaria, pagos.CtaOrdenante))
                                {
                                    result = "CRP213 - El campo CtaOrdenante no cumple con el patrón requerido.";
                                    return(result);
                                }
                            }
                        }
                        if (pagos.FormaDePagoP != "02" && pagos.FormaDePagoP != "03" && pagos.FormaDePagoP != "04" && pagos.FormaDePagoP != "05" && pagos.FormaDePagoP != "28" && pagos.FormaDePagoP != "29")
                        {
                            if (!string.IsNullOrEmpty(pagos.RfcEmisorCtaBen))
                            {
                                result = "CRP214 - El campo RfcEmisorCtaBen no se debe registrar.";
                                return(result);
                            }
                            if (!string.IsNullOrEmpty(pagos.CtaBeneficiario))
                            {
                                result = "CRP215 - El campo CtaBeneficiario no se debe registrar.";
                                return(result);
                            }
                        }
                        if (pagos.FormaDePagoP != "03" && pagos.TipoCadPagoSpecified)
                        {
                            result = "CRP216 - El campo TipoCadPago no se debe registrar. ";
                            return(result);
                        }
                        int tDoc = 0;
                        if (pagos.DoctoRelacionado != null)
                        {
                            tDoc = pagos.DoctoRelacionado.Count <PagosPagoDoctoRelacionado>();
                        }
                        if (pagos.DoctoRelacionado != null)
                        {
                            doctoRelacionado = pagos.DoctoRelacionado;
                            for (int i = 0; i < doctoRelacionado.Length; i++)
                            {
                                PagosPagoDoctoRelacionado doc = doctoRelacionado[i];
                                if (doc.MonedaDR == "XXX")
                                {
                                    result = "CRP217 - El valor del campo MonedaDR debe ser distinto de \"XXX\"";
                                    return(result);
                                }
                                if (doc.MonedaDR != pagos.MonedaP)
                                {
                                    if (!doc.TipoCambioDRSpecified)
                                    {
                                        result = "CRP218 - El campo TipoCambioDR se debe registrar.";
                                        return(result);
                                    }
                                }
                                else if (doc.TipoCambioDRSpecified)
                                {
                                    result = "CRP219 - El campo TipoCambioDR no se debe registrar.";
                                    return(result);
                                }
                                if (doc.MonedaDR == "MXN" && pagos.MonedaP != "MXN" && doc.TipoCambioDR != 1m)
                                {
                                    result = "CRP220 - El campo TipoCambioDR debe ser \"1\".";
                                    return(result);
                                }
                                if (doc.MetodoDePagoDR == "PPD")
                                {
                                    if (!doc.ImpSaldoAntSpecified)
                                    {
                                        result = "CRP234 - El campo ImpSaldoAnt se debe registrar.";
                                        return(result);
                                    }
                                }
                                if (tDoc > 1 && !doc.ImpPagadoSpecified)
                                {
                                    result = "CRP235 - El campo ImpPagado se debe registrar. ";
                                    return(result);
                                }
                                if (tDoc == 1 && doc.TipoCambioDRSpecified && !doc.ImpPagadoSpecified)
                                {
                                    result = "CRP235 - El campo ImpPagado se debe registrar. ";
                                    return(result);
                                }
                                if (doc.ImpSaldoAntSpecified)
                                {
                                    if (doc.ImpSaldoAnt <= 0m)
                                    {
                                        result = "CRP221 - El campo ImpSaldoAnt debe mayor a cero.";
                                        return(result);
                                    }
                                    string impSal = doc.ImpSaldoAnt.ToString();
                                    if (impSal != null)
                                    {
                                        if (impSal != "0")
                                        {
                                            string[] split = impSal.Split(".".ToCharArray());
                                            if (split.Count <string>() <= 1)
                                            {
                                                result = "CRP222 - El valor del campo ImpSaldoAnt debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                            if (split[1].Count <char>() != (int)Convert.ToInt16(mone.Decimales))
                                            {
                                                result = "CRP222 - El valor del campo ImpSaldoAnt debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                        }
                                    }
                                }
                                if (doc.ImpPagadoSpecified)
                                {
                                    if (doc.ImpPagado <= 0m)
                                    {
                                        result = "CRP223 - El campo ImpPagado debe mayor a cero.";
                                        return(result);
                                    }
                                    string impPa = doc.ImpPagado.ToString();
                                    if (impPa != null)
                                    {
                                        if (impPa != "0")
                                        {
                                            string[] split = impPa.Split(".".ToCharArray());
                                            if (split.Count <string>() <= 1)
                                            {
                                                result = "CRP224 - El valor del campo ImpPagado debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                            if (split[1].Count <char>() != (int)Convert.ToInt16(mone.Decimales))
                                            {
                                                result = "CRP224 - El valor del campo ImpPagado debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                        }
                                    }
                                }
                                if (doc.ImpSaldoInsolutoSpecified)
                                {
                                    string impSalI = doc.ImpSaldoInsoluto.ToString();
                                    if (impSalI != null)
                                    {
                                        if (impSalI != "0")
                                        {
                                            string[] split = impSalI.Split(".".ToCharArray());
                                            if (split.Count <string>() <= 1)
                                            {
                                                result = "CRP225 - El valor del campo ImpSaldoInsoluto debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                            if (split[1].Count <char>() != (int)Convert.ToInt16(mone.Decimales))
                                            {
                                                result = "CRP225 - El valor del campo ImpSaldoInsoluto debe tener hasta la cantidad de decimales que soporte la moneda registrada en el campo MonedaDR.";
                                                return(result);
                                            }
                                        }
                                    }
                                    if (doc.ImpSaldoInsoluto < 0m)
                                    {
                                        result = "CRP226 - El campo ImpSaldoInsoluto debe ser mayor o igual a cero y calcularse con la suma de los campos ImSaldoAnt menos el ImpPagado o el Monto.";
                                        return(result);
                                    }
                                    if (doc.ImpSaldoInsoluto != doc.ImpSaldoAnt - doc.ImpPagado)
                                    {
                                        result = "CRP226 - El campo ImpSaldoInsoluto debe ser mayor o igual a cero y calcularse con la suma de los campos ImSaldoAnt menos el ImpPagado o el Monto.";
                                        return(result);
                                    }
                                }
                            }
                        }
                        if (pagos.TipoCadPagoSpecified)
                        {
                            if (pagos.CertPago == null)
                            {
                                result = "CRP227 - El campo CertPago se debe registrar.";
                                return(result);
                            }
                            if (string.IsNullOrEmpty(pagos.CadPago))
                            {
                                result = "CRP229 - El campo CadPago se debe registrar.";
                                return(result);
                            }
                            if (pagos.SelloPago == null)
                            {
                                result = "CRP231 - El campo SelloPago se debe registrar. ";
                                return(result);
                            }
                        }
                        else
                        {
                            if (pagos.CertPago != null)
                            {
                                result = "CRP228 - El campo CertPago no se debe registrar.";
                                return(result);
                            }
                            if (!string.IsNullOrEmpty(pagos.CadPago))
                            {
                                result = "CRP230 - El campo CadPago no se debe registrar.";
                                return(result);
                            }
                            if (pagos.SelloPago != null)
                            {
                                result = "CRP232 - El campo SelloPago no se debe registrar.";
                                return(result);
                            }
                        }
                        if (pagos.DoctoRelacionado != null)
                        {
                            doctoRelacionado = pagos.DoctoRelacionado;
                            for (int i = 0; i < doctoRelacionado.Length; i++)
                            {
                                PagosPagoDoctoRelacionado doc = doctoRelacionado[i];
                                if (doc.MetodoDePagoDR == "PPD")
                                {
                                    if (string.IsNullOrEmpty(doc.NumParcialidad))
                                    {
                                        result = "CRP233 - El campo NumParcialidad se debe registrar.";
                                        return(result);
                                    }
                                    if (!doc.ImpSaldoInsolutoSpecified)
                                    {
                                        result = "CRP236 - El campo ImpSaldoInsoluto se debe registrar.";
                                        return(result);
                                    }
                                }
                            }
                        }
                        if (pagos.Impuestos != null)
                        {
                            result = "CRP237 - No debe existir el apartado de Impuestos.";
                            return(result);
                        }
                        if (pagos.FormaDePagoP != "02" && pagos.FormaDePagoP != "03" && pagos.FormaDePagoP != "04" && pagos.FormaDePagoP != "05" && pagos.FormaDePagoP != "06" && pagos.FormaDePagoP != "28" && pagos.FormaDePagoP != "29" && !string.IsNullOrEmpty(pagos.RfcEmisorCtaOrd))
                        {
                            result = "CRP238 - El campo RfcEmisorCtaOrd no se debe registrar.";
                            return(result);
                        }
                        if (!string.IsNullOrEmpty(pagos.CtaBeneficiario))
                        {
                            OperacionesCatalogos     o10       = new OperacionesCatalogos();
                            CatalogosSAT.c_FormaPago formaPago = o10.Consultar_FormaPago(pagos.FormaDePagoP);
                            if (formaPago.PatroncuentaBeneficiaria != "No" && formaPago.PatroncuentaBeneficiaria != "Opcional")
                            {
                                if (!this.validarExpresion(formaPago.PatroncuentaBeneficiaria, pagos.CtaBeneficiario))
                                {
                                    result = "CRP239 - El campo CtaBeneficiario no cumple con el patrón requerido.";
                                    return(result);
                                }
                            }
                        }
                    }
                    result = "0";
                }
            }
            return(result);
        }//-------------------------------------------------------------------------------------
        public string TimbraCfdi(string userName, string password, string comprobante)
        {
            string erroresNomina = "0";

            if (!this.ValidCredentials(userName, password))
            {
                throw new UnauthorizedAccessException("Invalid Ntlink internal user and password combination");
            }
            string result2;

            try
            {
                XElement element = XElement.Load(new StringReader(comprobante));
                ServicioLocal.Business.Comprobante comp = this.DesSerializar(element);
                if (comprobante.Contains("<ieeh:IngresosHidrocarburos"))
                {
                    string erroIH = "";
                    IngresosHidrocarburos       I  = this.DesSerializarIH(element, ref erroIH);
                    ValidarIngresoHidrocarburos VI = new ValidarIngresoHidrocarburos();
                    erroIH = VI.ProcesarIngresoHidrocarburos(I, comp.Version, comp.TipoDeComprobante, comp.Total);
                    if (erroIH != "0")
                    {
                        result2 = erroIH;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<gceh:GastosHidrocarburos"))
                {
                    string erroGH = "";
                    GastosHidrocarburos        I2  = this.DesSerializarGH(element, ref erroGH);
                    ValidarGastosHidrocarburos VI2 = new ValidarGastosHidrocarburos();
                    erroGH = VI2.ProcesarGastosHidrocarburos(I2, comp.Version, comp.TipoDeComprobante);
                    if (erroGH != "0")
                    {
                        result2 = erroGH;
                        return(result2);
                    }
                }
                ImpuestosLocales IL = null;
                if (comprobante.Contains("<implocal:ImpuestosLocales"))
                {
                    IL = this.DesSerializarImpuestosLocales(element);
                }
                bool pago10 = comprobante.Contains("pago10:Pagos");
                if (pago10)
                {
                    ServicioLocal.Business.Pagoo.Comprobante pagoDatos = this.DesSerializarP(element);
                    ServicioLocal.Business.Complemento.Pagos pagoss    = this.DesSerializarPagos(element);
                    ValidarPago VP         = new ValidarPago();
                    string      ErrorPagos = VP.ProcesarPago(comp, pagoss, pagoDatos);
                    if (ErrorPagos != "0")
                    {
                        result2 = ErrorPagos;
                        return(result2);
                    }
                }
                if (comprobante.Contains("<ine:INE "))
                {
                    string     erroINE = "";
                    INE        I3      = this.DesSerializarINE(element, ref erroINE);
                    ValidarINE VI3     = new ValidarINE();
                    erroINE = VI3.ProcesarINE(I3);
                    if (erroINE != "0")
                    {
                        result2 = erroINE;
                        return(result2);
                    }
                }
                bool          ComerExt    = comprobante.Contains("cce11:ComercioExterior");
                ValidarCFDI33 valida      = new ValidarCFDI33();
                string        errorCFDI33 = valida.ProcesarCFDI33(comp, comprobante, pago10, ComerExt, IL);
                if (errorCFDI33 != "0")
                {
                    CertificadorApps.Logger.Error("Error al abrir el comprobante: " + errorCFDI33);
                    result2 = errorCFDI33;
                }
                else
                {
                    if (comprobante.Contains("<ecc12:EstadoDeCuentaCombustible"))
                    {
                        string erroECC = "";
                        EstadoDeCuentaCombustible E = this.DesSerializarECC(element, ref erroECC);
                        ValidarECC VE = new ValidarECC();
                        erroECC = VE.ProcesarECC(E, comp.TipoDeComprobante, comp.Version);
                        if (erroECC != "0")
                        {
                            result2 = erroECC;
                            return(result2);
                        }
                    }
                    if (comp.Emisor != null && comp.Emisor.Rfc != null)
                    {
                        empresa empresa = TimbradoUtils.ValidarUsuarioSinSaldo(comp.Emisor.Rfc);
                        if (empresa == null)
                        {
                            CertificadorApps.Logger.Info(comp.Emisor.Rfc + " No encontrado");
                            result2 = "300 - El usuario con el que se quiere conectar es inválido";
                        }
                        else
                        {
                            string result = null;
                            TimbreFiscalDigital timbre = null;
                            string        acuseSat     = "";
                            string        hash         = null;
                            bool          nomin12      = comprobante.Contains("nomina12:Nomina");
                            List <Nomina> nom          = new List <Nomina>();
                            if (nomin12)
                            {
                                string erroresNom = null;
                                var    nomx       = this.DesSerializarNomina12(element, ref erroresNom);
                                nom.Add(nomx);
                                if (erroresNom != null)
                                {
                                    result2 = erroresNom;
                                    return(result2);
                                }
                            }
                            if (ComerExt && erroresNomina == "0")
                            {
                                string erroresComer           = null;
                                ValidarComercioExterior val   = new ValidarComercioExterior();
                                ComercioExterior        Comer = this.DesSerializarComercioExterior(element, ref erroresComer);
                                if (erroresComer != null)
                                {
                                    CertificadorApps.Logger.Error("Error al abrir el comprobante: " + erroresComer);
                                    result2 = erroresComer;
                                    return(result2);
                                }
                                erroresNomina = val.ProcesarComercioExterior(Comer, comp);
                            }
                            if (nomin12 && erroresNomina == "0")
                            {
                                erroresNomina = this._val.ProcesarNomina(nom, comp);
                            }
                            if (erroresNomina == "0")
                            {
                                Dictionary <int, string> dict = this._val.ProcesarCadena(comp.Emisor.Rfc, comprobante, ref result, ref timbre, ref acuseSat, ref hash);
                                if (timbre != null && timbre.SelloSAT != null && dict.Count == 0)
                                {
                                    if (!string.IsNullOrEmpty(comp.Confirmacion))
                                    {
                                        using (NtLinkLocalServiceEntities db = new NtLinkLocalServiceEntities())
                                        {
                                            ConfirmacionTimbreWs33 C = db.ConfirmacionTimbreWs33.FirstOrDefault((ConfirmacionTimbreWs33 p) => p.Folio == comp.Folio && p.RfcEmisor == comp.Emisor.Rfc && p.RfcReceptor == comp.Receptor.Rfc);
                                            C.procesado = new bool?(true);
                                            db.ConfirmacionTimbreWs33.ApplyCurrentValues(C);
                                            db.SaveChanges();
                                        }
                                    }
                                    SerializadorTimbres sert = new SerializadorTimbres();
                                    if (ConfigurationManager.AppSettings["Pruebas"] == "true")
                                    {
                                        timbre.SelloSAT = "Inválido, Ambiente de pruebas";
                                    }
                                    string res          = sert.GetTimbreXml(timbre);
                                    string cfdiTimbrado = result;
                                    if (ConfigurationManager.AppSettings["EnvioSat"] == "false")
                                    {
                                        if (!TimbradoUtils.GuardaFactura(comp.Fecha, comp.Emisor.Rfc, comp.Receptor.Rfc, timbre.UUID, cfdiTimbrado, hash, empresa, false, false))
                                        {
                                            throw new Exception("Error al abrir el comprobante");
                                        }
                                    }
                                    result2 = res;
                                }
                                else
                                {
                                    if (timbre != null && timbre.SelloSAT == null && dict.Count == 0)
                                    {
                                        XElement el          = XElement.Parse(result);
                                        XElement complemento = el.Elements(Constantes.CFDVersionNamespace + "Complemento").FirstOrDefault <XElement>();
                                        if (complemento != null)
                                        {
                                            XElement t = complemento.Elements(Constantes.CFDTimbreFiscalVersionNamespace + "TimbreFiscalDigital").FirstOrDefault <XElement>();
                                            if (t != null)
                                            {
                                                SidetecStringWriter sw = new SidetecStringWriter(Encoding.UTF8);
                                                t.Save(sw, SaveOptions.DisableFormatting);
                                                result2 = sw.ToString();
                                                return(result2);
                                            }
                                        }
                                    }
                                    if (dict.Count > 0)
                                    {
                                        StringBuilder res2 = new StringBuilder();
                                        foreach (KeyValuePair <int, string> d in dict)
                                        {
                                            res2.AppendLine(d.Key.ToString() + " - " + d.Value.ToString());
                                        }
                                        result2 = res2.ToString();
                                    }
                                    else
                                    {
                                        CertificadorApps.Logger.Error("Error al abrir el comprobante: " + comprobante);
                                        result2 = "Error al abrir el comprobante";
                                    }
                                }
                            }
                            else
                            {
                                CertificadorApps.Logger.Error("Error al abrir el comprobante: " + erroresNomina);
                                result2 = erroresNomina;
                            }
                        }
                    }
                    else
                    {
                        CertificadorApps.Logger.Error("Error al abrir el comprobante: " + comprobante);
                        result2 = "Error al abrir el comprobante";
                    }
                }
            }
            catch (Exception ex)
            {
                CertificadorApps.Logger.Error(ex);
                result2 = "Error al abrir el comprobante";
            }
            return(result2);
        }