コード例 #1
0
        public Convenio ObtenerConvenioModificatorio(string folioConvenio, ref string msjError)
        {
            Convenio Convenio      = new Convenio();
            int      folioContrato = 0;
            int      IdConvenio    = 0;

            try
            {
                int.TryParse(folioConvenio.Split('-')[0], out folioContrato);
                int.TryParse(folioConvenio.Split('-')[1], out IdConvenio);

                if (folioContrato == 0 || IdConvenio == 0)
                {
                    msjError = "No se encuentra la información del convenio modificatorio. Favor de contactar a tu administrador";
                    return(new Convenio());
                }

                using (ArrendamientoInmuebleEntities aInmueble = new ArrendamientoInmuebleEntities())
                {
                    Convenio = aInmueble.Convenio_Modificatorio.Where(x => x.ContratoArrto.FolioContratoArrto == folioContrato && x.IdConvenio == IdConvenio).Select(x => new Convenio
                    {
                        IdConvenio          = x.IdConvenioModif,
                        IdInmueble          = x.ContratoArrto.Fk_IdInmuebleArrendamiento,
                        FolioConvenio       = folioConvenio,
                        FolioContrato       = x.ContratoArrto.FolioContratoArrto,
                        ConsecutivoConvenio = x.IdConvenio,
                        FechaConvenio       = x.FechaConvenio == null ? new DateTime() : x.FechaConvenio.Value,
                        FechaTermino        = x.FechaTerminacion,
                        SupM2               = x.Nueva_Superficie,
                        Secuencial          = x.Fk_IdJustipreciacion,
                        ImporteRenta        = x.Importe_Renta,
                        FechaEfectoConvenio = x.FechaEfecConvenio,
                        NombreOIC           = x.Nombre,
                        PApellidoOIC        = x.Primer_Apellido,
                        SApellidoOIC        = x.Segundo_Apellido,
                        CargoOIC            = x.Nombre_Cargo,
                        CorreoOIC           = x.Email,
                        FechaRegistro       = x.FechaRegistro,
                    }).FirstOrDefault();

                    Convenio.descFechaTermino        = Convenio.FechaTermino == null ? "" : Convenio.FechaTermino.Value.ToString("d");
                    Convenio.descFechaRegistro       = Convenio.FechaRegistro.ToString("d");
                    Convenio.DescFechaEfectoConvenio = Convenio.FechaEfectoConvenio.ToString("d");

                    SelloDigital sDigital = aInmueble.SelloDigital.Where(x => x.EstatusRegistro == true && x.Fk_IdCatTabla == 4 && x.Fk_IdRegistroTablaOrigen == Convenio.IdConvenio).FirstOrDefault();

                    Convenio.cadOriginal           = sDigital.CadenaOriginal;
                    Convenio.Sello                 = sDigital.SelloDigital1;
                    Convenio.QR                    = sDigital.QR;
                    Convenio.descFechaAutorizacion = sDigital.FechaRegistro.ToString("d");
                }
            }

            catch (Exception ex)
            {
                throw new Exception(string.Format("ObtenerConvenioModificatorio:{0}", ex.Message));
            }

            return(Convenio);
        }
コード例 #2
0
ファイル: XML.cs プロジェクト: jorgecb/algunproyecto
        /// <summary>
        /// Obtener cadena del Certificado del archivo .cer
        /// </summary>
        /// <returns>Cadena del certificados</returns>
        private string ObtenerCertificado()
        {
            string       respuesta;
            SelloDigital sello = new SelloDigital();

            try
            {
                respuesta = sello.Certificado(_facturaRutaCer);
            }
            catch
            {
                respuesta = string.Empty;
            }
            return(respuesta);
        }
コード例 #3
0
        public bool AutorizarConvenioModificatorio(int IdConvenioModificatorio, string CadOrignal, string Sello, string QR, int IdUsuario, ref string fechaRegistro)
        {
            bool respuesta = false;

            try
            {
                using (ArrendamientoInmuebleEntities aInmueble = new ArrendamientoInmuebleEntities())
                {
                    Convenio_Modificatorio cModificatorio = aInmueble.Convenio_Modificatorio.Where(x => x.IdConvenioModif == IdConvenioModificatorio).FirstOrDefault();

                    if (cModificatorio != null)
                    {
                        using (TransactionScope transaccion = new TransactionScope())
                        {
                            SelloDigital sello = new SelloDigital
                            {
                                Fk_IdCatTabla            = 4,
                                Fk_IdRegistroTablaOrigen = IdConvenioModificatorio,
                                CadenaOriginal           = CadOrignal,
                                SelloDigital1            = Sello,
                                GUID                 = Guid.NewGuid().ToString(),
                                EstatusRegistro      = true,
                                FechaRegistro        = DateTime.Now,
                                Fk_IdUsuarioRegistro = IdUsuario,
                                QR = QR
                            };

                            aInmueble.SelloDigital.Add(sello);
                            aInmueble.SaveChanges();

                            fechaRegistro = sello.FechaRegistro.ToString("d");

                            transaccion.Complete();
                            respuesta = true;
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                throw new Exception(string.Format("GenerarConvenioModificatorio:{0}", ex.Message));
            }

            return(respuesta);
        }
コード例 #4
0
ファイル: ObtenerNodos.cs プロジェクト: jorgecb/algunproyecto
        /// <summary>
        /// Obtener número de certificado del Certificado Emisor
        /// </summary>
        /// <returns>Cadena con número de certificado</returns>
        private string ObtenerNumeroCertificado()
        {
            string respuesta, aa, b, c;

            try
            {
                if (!SelloDigital.LeerCER(_facturaRutaCer, out aa, out b, out c, out respuesta))
                {
                    respuesta = string.Empty;
                }
            }
            catch
            {
                respuesta = string.Empty;
            }

            return(respuesta);
        }
コード例 #5
0
ファイル: CFDI.cs プロジェクト: gultekincenter/PointOfSale-3
        //Inicizalizar
        public void Inicializar()
        {
            //Controladores
            ventaController    = new VentaController();
            ventapController   = new VentapController();
            clienteController  = new ClienteController();
            empresaController  = new EmpresaController();
            dymErrorController = new DymErrorController();

            //Utils
            respuestaCFDI  = new RespuestaCFDi();
            timbradoClient = new TimbradoClient();
            selloDigital   = new SelloDigital();
            transformador  = new XslCompiledTransform();

            //Comprobante
            comprobante = new Comprobante();
            emisor      = new ComprobanteEmisor();
            receptor    = new ComprobanteReceptor();


            // Nivel concepto
            conceptos         = new List <ComprobanteConcepto>();
            concepto          = new ComprobanteConcepto();
            impuestosConcepto = new List <ComprobanteConceptoImpuestosTraslado>();
            ivaConcepto       = new ComprobanteConceptoImpuestosTraslado();
            iepsConcepto      = new ComprobanteConceptoImpuestosTraslado();



            //Nivel comprobante
            impuestosComprobante      = new List <ComprobanteImpuestosTraslado>();
            totalImpuestosComprobante = new ComprobanteImpuestos();
            ivaComprobante            = new ComprobanteImpuestosTraslado();
            iepsComprobante           = new ComprobanteImpuestosTraslado();


            //inicializacion de propiedades
            empresa  = empresaController.SelectTopOne();
            partidas = ventapController.SelectPartidas(Venta.VentaId);
            cliente  = clienteController.SelectOne(Venta.ClienteId);
            s        = "";
        }
コード例 #6
0
        //private Comprobante asignarCertificado(Comprobante comprobante, RazonesSociales razonSocial)
        private Comprobante asignarCertificado(Comprobante comprobante, Certificados certificado)
        {
            string       numeroCertificado, aa, b, c;
            SelloDigital oSelloDigital = new SelloDigital();

            if (comprobante == null)
            {
                comprobante = new Comprobante();
            }

            try
            {
                /*if (razonSocial.certificadoSAT == null)
                 * {
                 *  comprobante.Certificado = oSelloDigital.Certificado(razonSocial.rutaCert);
                 *  SelloDigital.leerCER(razonSocial.rutaCert, out aa, out b, out c, out numeroCertificado);
                 *  comprobante.NoCertificado = numeroCertificado;
                 * }
                 * else
                 * {
                 *  comprobante.Certificado = oSelloDigital.Certificado(razonSocial.certificadoSAT);
                 *  SelloDigital.leerCER(razonSocial.certificadoSAT, out aa, out b, out c, out numeroCertificado);
                 *  comprobante.NoCertificado = numeroCertificado;
                 * }
                 *
                 * comprobante.NoCertificado = numeroCertificado; */
                comprobante.Certificado = oSelloDigital.Certificado(certificado.certificado);
                SelloDigital.leerCER(certificado.certificado, out aa, out b, out c, out numeroCertificado);
                comprobante.NoCertificado = numeroCertificado;
            }
            catch (Exception ex)
            {
                //utilSat.bitacora(ex.getMessage());
                //erroresArchivos.append(ex.getMessage().concat("|"));
                //  System.err.println(concatena.delete(0, concatena.length()).append(msgError).append("asignarCertificado()1_Error: ").append(ex));
            }

            return(comprobante);
        }
コード例 #7
0
        public Mensaje getDatosCertificados(byte[] ArchivoCER, byte[] ArchivoKEY, string ClavePrivada, DBContextAdapter dbContext)
        {
            try
            {
                inicializaVariableMensaje();
                SelloDigital  oSelloDigital = new SelloDigital();
                string        numeroCertificado, c;
                DateTime      aa, b;
                List <object> listResultado = new List <object>();

                bool rest     = SelloDigital.leerCertDate(ArchivoCER, out aa, out b, out c, out numeroCertificado);
                bool coincide = SelloDigital.validarCERKEYARCHIVO(ArchivoKEY, ClavePrivada);

                listResultado.Add(aa);
                listResultado.Add(b);
                listResultado.Add(c);
                listResultado.Add(numeroCertificado);
                listResultado.Add(coincide);
                listResultado.Add(rest);



                mensajeResultado.resultado = listResultado;
                mensajeResultado.noError   = 0;
                mensajeResultado.error     = "";
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(concatena.Remove(0, concatena.Length).Append(msgError).Append("getDatosCertificados()1_Error: ").Append(ex));
                mensajeResultado.noError   = ControlErroresEntity.buscaNoErrorPorExcepcion(ex);
                mensajeResultado.error     = ex.GetBaseException().ToString();
                mensajeResultado.resultado = null;
            }



            return(mensajeResultado);
        }
コード例 #8
0
        public static void CreaFactura()
        {
            string pathCer      = Directory.GetCurrentDirectory() + @"/Fiel/Certifiado.cer";
            string pathKey      = Directory.GetCurrentDirectory() + @"/Fiel/Key.key";
            string clavePrivada = "12345678a";

            //Obtenemos el numero
            string numeroCertificado, aa, b, c;

            SelloDigital.leerCER(pathCer, out aa, out b, out c, out numeroCertificado);


            //Llenamos la clase COMPROBANTE--------------------------------------------------------
            Comprobante oComprobante = new Comprobante();

            oComprobante.Version = "3.3";
            oComprobante.Serie   = "H";
            oComprobante.Folio   = "1";
            oComprobante.Fecha   = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
            // oComprobante.Sello = "faltante"; //sig video
            oComprobante.FormaPago     = "1";
            oComprobante.NoCertificado = numeroCertificado;
            // oComprobante.Certificado = ""; //sig video
            oComprobante.SubTotal          = 10m;
            oComprobante.Moneda            = "MXN";
            oComprobante.Total             = 10;
            oComprobante.TipoDeComprobante = "I";
            oComprobante.MetodoPago        = "PUE";
            oComprobante.LugarExpedicion   = "44860";



            ComprobanteEmisor oEmisor = new ComprobanteEmisor();

            oEmisor.Rfc           = "AATJ9502061EA";
            oEmisor.Nombre        = "Jorge Humberto Alvarado Tostado";
            oEmisor.RegimenFiscal = "612";

            ComprobanteReceptor oReceptor = new ComprobanteReceptor();

            oReceptor.Nombre  = "Pepe SA DE CV";
            oReceptor.Rfc     = "BIO091204LB1";
            oReceptor.UsoCFDI = "G03";

            //asigno emisor y receptor
            oComprobante.Emisor   = oEmisor;
            oComprobante.Receptor = oReceptor;


            List <ComprobanteConcepto> lstConceptos = new List <ComprobanteConcepto>();
            ComprobanteConcepto        oConcepto    = new ComprobanteConcepto();

            oConcepto.Importe       = 10m;
            oConcepto.ClaveProdServ = "92111704";
            oConcepto.Cantidad      = 1;
            oConcepto.ClaveUnidad   = "H87";
            oConcepto.Descripcion   = "Un misil para la guerra";
            oConcepto.ValorUnitario = 10m;


            lstConceptos.Add(oConcepto);

            oComprobante.Conceptos = lstConceptos.ToArray();


            //Creamos el xml
            CreateXML(oComprobante);

            string cadenaOriginal = "";
            string pathxsl        = Directory.GetCurrentDirectory() + @"/Fiel/cadenaoriginal_3_3.xslt";

            System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
            transformador.Load(pathxsl);

            using (StringWriter sw = new StringWriter())
                using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                {
                    transformador.Transform(pathXML, xwo);
                    cadenaOriginal = sw.ToString();
                }


            SelloDigital oSelloDigital = new SelloDigital();

            oComprobante.Certificado = oSelloDigital.Certificado(pathCer);
            oComprobante.Sello       = oSelloDigital.Sellar(cadenaOriginal, pathKey, clavePrivada);

            CreateXML(oComprobante);

            ////TIMBRE DEL XML
            ServiceReferenceFC.RespuestaCFDi respuestaCFDI = new ServiceReferenceFC.RespuestaCFDi();

            byte[] bXML = System.IO.File.ReadAllBytes(pathXML);

            ServiceReferenceFC.TimbradoClient oTimbrado = new ServiceReferenceFC.TimbradoClient();

            respuestaCFDI = oTimbrado.TimbrarTest("TEST010101ST1", "a", bXML);

            if (respuestaCFDI.Documento == null)
            {
                Console.WriteLine(respuestaCFDI.Mensaje);
            }
            else
            {
                System.IO.File.WriteAllBytes(pathXML, respuestaCFDI.Documento);
            }
        }
コード例 #9
0
        public static string CreaFactura(string folio, string formaPago, string metodoDePago, List <ProductoSat> productos, float subtotal, string rfc, string rz, string usoCFDI, string mail)
        {
            string pathCer      = Directory.GetCurrentDirectory() + @"/Fiel/Certifiado.cer";
            string pathKey      = Directory.GetCurrentDirectory() + @"/Fiel/Key.key";
            string clavePrivada = "Jorge1995";

            //Obtenemos el numero
            string numeroCertificado, aa, b, c;

            SelloDigital.leerCER(pathCer, out aa, out b, out c, out numeroCertificado);


            //Llenamos la clase COMPROBANTE--------------------------------------------------------
            string      subt            = subtotal.ToString();
            string      impuetosImporte = (subtotal * 0.16).ToString();
            float       t            = subtotal * 1.16f;
            string      ts           = t.ToString();
            Comprobante oComprobante = new Comprobante();

            oComprobante.Version = "3.3";
            oComprobante.Serie   = "H";
            oComprobante.Folio   = folio;
            oComprobante.Fecha   = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
            //oComprobante.Fecha = "2019-06-11T10:52:20";
            //oComprobante.Sello = "faltante"; //sig video
            oComprobante.FormaPago     = formaPago;
            oComprobante.NoCertificado = numeroCertificado;
            // oComprobante.Certificado = ""; //sig video
            oComprobante.SubTotal          = decimal.Parse(subt);
            oComprobante.Moneda            = "MXN";
            oComprobante.Total             = decimal.Parse(ts);
            oComprobante.TipoDeComprobante = "I";
            oComprobante.MetodoPago        = "PUE";
            oComprobante.LugarExpedicion   = "44860";



            ComprobanteEmisor oEmisor = new ComprobanteEmisor();

            oEmisor.Rfc           = "AATJ9502061EA";
            oEmisor.Nombre        = "Jorge Humberto Alvarado Tostado";
            oEmisor.RegimenFiscal = "612";

            ComprobanteReceptor oReceptor = new ComprobanteReceptor();

            oReceptor.Nombre  = rz;
            oReceptor.Rfc     = rfc;
            oReceptor.UsoCFDI = usoCFDI;

            //asigno emisor y receptor
            oComprobante.Emisor   = oEmisor;
            oComprobante.Receptor = oReceptor;


            List <ComprobanteConcepto>           lstConceptos = new List <ComprobanteConcepto>();
            ComprobanteConcepto                  oConcepto;
            ComprobanteConceptoImpuestos         impuestos;
            ComprobanteConceptoImpuestosTraslado imAux;

            ComprobanteConceptoImpuestosTraslado[] impuestosTrasladados;

            foreach (ProductoSat a in productos)
            {
                oConcepto               = new ComprobanteConcepto();
                impuestos               = new ComprobanteConceptoImpuestos();
                imAux                   = new ComprobanteConceptoImpuestosTraslado();
                impuestosTrasladados    = new ComprobanteConceptoImpuestosTraslado[1];
                oConcepto.Importe       = Math.Round(decimal.Parse((a.Subtotal).ToString()), 3);
                oConcepto.ClaveProdServ = a.CodigoSAT;
                oConcepto.Cantidad      = decimal.Parse(a.Cantidad.ToString());
                oConcepto.ClaveUnidad   = "H87";
                oConcepto.Descripcion   = a.Descripcion;
                oConcepto.ValorUnitario = decimal.Parse((a.Precio).ToString());
                //Impuestos
                imAux.Base                = decimal.Parse(a.Subtotal.ToString());
                imAux.ImporteSpecified    = true;
                imAux.TasaOCuotaSpecified = true;
                imAux.TipoFactor          = "Tasa";
                imAux.Importe             = Math.Round(decimal.Parse((a.Subtotal * 0.16).ToString()), 3);
                imAux.TasaOCuota          = decimal.Parse("0.160000");
                imAux.Impuesto            = "002";
                impuestosTrasladados[0]   = imAux;
                impuestos.Traslados       = impuestosTrasladados;
                oConcepto.Impuestos       = impuestos;
                lstConceptos.Add(oConcepto);
            }
            oComprobante.Conceptos = lstConceptos.ToArray();

            ComprobanteImpuestos         imComprobante           = new ComprobanteImpuestos();
            ComprobanteImpuestosTraslado imComprobanteTraladados = new ComprobanteImpuestosTraslado();

            ComprobanteImpuestosTraslado[] imComprobanteTraladadosArray = new ComprobanteImpuestosTraslado[1];

            imComprobanteTraladados.TipoFactor = "Tasa";
            imComprobanteTraladados.TasaOCuota = decimal.Parse("0.160000");
            imComprobanteTraladados.Impuesto   = "002";
            imComprobanteTraladados.Importe    = Math.Round(decimal.Parse(impuetosImporte), 3);

            imComprobanteTraladadosArray[0] = imComprobanteTraladados;

            imComprobante.Traslados = imComprobanteTraladadosArray;

            imComprobante.TotalImpuestosTrasladadosSpecified = true;
            imComprobante.TotalImpuestosTrasladados          = Math.Round(decimal.Parse(impuetosImporte), 2);
            oComprobante.Impuestos = imComprobante;



            //Creamos el xml
            CreateXML(oComprobante);

            string cadenaOriginal = "";
            string pathxsl        = Directory.GetCurrentDirectory() + @"/Fiel/cadenaoriginal_3_3.xslt";

            System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
            transformador.Load(pathxsl);

            using (StringWriter sw = new StringWriter())
                using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                {
                    transformador.Transform(pathXML, xwo);
                    cadenaOriginal = sw.ToString();
                }


            SelloDigital oSelloDigital = new SelloDigital();

            oComprobante.Certificado = oSelloDigital.Certificado(pathCer);
            oComprobante.Sello       = oSelloDigital.Sellar(cadenaOriginal, pathKey, clavePrivada);

            CreateXML(oComprobante);

            ////TIMBRE DEL XML
            ServiceReferenceFC.RespuestaCFDi respuestaCFDI = new ServiceReferenceFC.RespuestaCFDi();

            byte[] bXML = System.IO.File.ReadAllBytes(pathXML);

            ServiceReferenceFC.TimbradoClient oTimbrado = new ServiceReferenceFC.TimbradoClient();

            respuestaCFDI = oTimbrado.Timbrar("AATJ9502061EA", "827984aaddd4126c9c67", bXML);

            if (respuestaCFDI.Documento == null)
            {
                return(respuestaCFDI.Mensaje);
            }
            else
            {
                System.IO.File.WriteAllBytes(pathXML, respuestaCFDI.Documento);
                ServiceReferenceFC.TimbradoClient pdf = new ServiceReferenceFC.TimbradoClient();
                bXML          = System.IO.File.ReadAllBytes(pathXML);
                respuestaCFDI = pdf.PDF("AATJ9502061EA", "827984aaddd4126c9c67", bXML, null);
                System.IO.File.WriteAllBytes(pathPDF, respuestaCFDI.Documento);
                Sql.InsertarFactura(folio, bXML);
                Sql.InsertarDatos("UPDATE  `venta` SET `facturada`= 1 WHERE id_venta=" + folio);
                string pXMl = @path + "\\" + folio + ".xml";
                string pPDF = @path + "\\" + folio + ".pdf";
                File.Move(pathXML, pXMl);
                File.Move(pathPDF, pPDF);
                try
                {
                    Email(mail, pXMl, pPDF);
                }
                catch (Exception e)
                {
                    return("Error: " + e.Message);
                }

                File.Delete(pXMl);
                File.Delete(pPDF);
            }
            return("");
        }
コード例 #10
0
        private static void Main(string[] args)
        {
            if (Environment.GetCommandLineArgs().Length != 7)
            {
                string commandLineArg1 = Environment.GetCommandLineArgs()[1]; //aztektimbra
                string commandLineArg2 = Environment.GetCommandLineArgs()[2]; //directorio .cer
                string commandLineArg3 = Environment.GetCommandLineArgs()[3]; //directorio .key
                string commandLineArg4 = Environment.GetCommandLineArgs()[4]; //firectorio paswword
                string commandLineArg5 = Environment.GetCommandLineArgs()[5]; //directorio xml.xml
                string commandLineArg6 = Environment.GetCommandLineArgs()[6]; //directorio serie+folio+.xml
                string commandLineArg7 = Environment.GetCommandLineArgs()[7]; //ruta .xslt
                byte[] numArray1       = (byte[])null;

                //Imprime un fichero con los argumentos pasados por AztekCFDI.
                System.IO.File.WriteAllText(@"C:\\cfdi\\Ruta-Timbrado.txt", commandLineArg1 + " - " + commandLineArg2 + " - " + commandLineArg3 + " - " + commandLineArg5 + " - " + commandLineArg6 + " - " + commandLineArg7);

                //Carga el transformador xslt
                string CadenaOriginal = "";
                System.Xml.Xsl.XslCompiledTransform transformador = new System.Xml.Xsl.XslCompiledTransform(true);
                transformador.Load(commandLineArg7);

                //Carga el xml y obtiene la Cadena-orginal
                using (StringWriter sw = new StringWriter())
                    using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                    {
                        transformador.Transform(commandLineArg5, xwo);
                        CadenaOriginal = sw.ToString();
                        System.IO.File.WriteAllText(@"C:\\cfdi\\Cadena-Original.txt", CadenaOriginal);
                    }

                //Se declara la variable par el sello y se guardan en un ficheros con el valor de retorno.
                string       selloCFD      = "";
                SelloDigital oSelloDigital = new SelloDigital();

                selloCFD = oSelloDigital.Sellar(CadenaOriginal, commandLineArg3, commandLineArg4);
                System.IO.File.WriteAllText(@"C:\\cfdi\\Sello-Emisor.txt", selloCFD);

                //Se leé el xml  generado por AztekCFDI
                FileStream  fileStream1 = new FileStream(commandLineArg5, FileMode.OpenOrCreate, FileAccess.Read);
                XmlDocument oXML        = new XmlDocument();
                oXML.Load((Stream)fileStream1);

                if (commandLineArg1 == "aztektimbra")
                {
                    //Si algo sale mal se imprime un fichero y se muestra el error en consola
                    if (selloCFD == null)
                    {
                        Console.Write("Error en sellado");
                        Console.ReadKey();
                        System.IO.File.WriteAllText(commandLineArg6 + ".resp", "Error en sellado");
                        Environment.Exit(0);
                    }

                    //Se leén los atributos del xml y modifica con los valores obtenidos.
                    oXML.ChildNodes[1].Attributes["Sello"].Value = selloCFD;

                    X509Certificate2 x509Certificate2 = new X509Certificate2(commandLineArg2);

                    if (x509Certificate2 != null)
                    {
                        string base64String = Convert.ToBase64String(x509Certificate2.RawData);

                        //Reescribe el xml con los atributos modificados.
                        numArray1 = Encoding.UTF8.GetBytes(oXML.InnerXml);
                        FileStream   fileStream2  = new FileStream(commandLineArg6, FileMode.Create, FileAccess.ReadWrite);
                        BinaryWriter binaryWriter = new BinaryWriter((Stream)fileStream2, Encoding.Unicode);
                        fileStream2.Position = 0L;
                        binaryWriter.Write(numArray1);
                        binaryWriter.Close();
                        fileStream2.Close();
                    }

                    // Se cierran  los archivos usados.
                    StreamReader streamReader = new StreamReader(commandLineArg6);
                    string       end          = streamReader.ReadToEnd();
                    streamReader.Close();
                    FileStream fileStream3 = new FileStream(commandLineArg2, FileMode.Open, FileAccess.Read);
                    int        length1     = (int)fileStream3.Length;
                    byte[]     numArray2   = new byte[length1];
                    int        num         = fileStream3.Read(numArray2, 0, length1);
                    fileStream3.Close();
                    FileStream fileStream4 = new FileStream(commandLineArg3, FileMode.Open, FileAccess.Read);
                    int        length2     = (int)fileStream4.Length;
                    byte[]     numArray3   = new byte[length2];
                    num = fileStream4.Read(numArray3, 0, length2);
                    fileStream4.Close();

                    //Cargamos el XML sellado  en una matriz  y lo convierte en Base64
                    byte[] rutaxmlsellado = System.IO.File.ReadAllBytes(commandLineArg6);
                    string xmlBase64      = Convert.ToBase64String(rutaxmlsellado);

                    //Imprime un fichero con el resultado de la converción del XML sellado.
                    System.IO.File.WriteAllText(@"C:\\cfdi\\xmlBase64.txt", xmlBase64);

                    /*
                     * //---------------nicia proceso de timbrado del XML---------------
                     * //Crear el objeto cliente
                     * ServiceReference1.timbrado_cfdi33_portClient cliente_timbrar = new ServiceReference1.timbrado_cfdi33_portClient();
                     *
                     * //Crear el objeto de la respuesta
                     *
                     * ServiceReference1.timbrar_cfdi_result response = new ServiceReference1.timbrar_cfdi_result();
                     *
                     *
                     * //llamar el método de timbrado enviándole los
                     * //parámetros con las credenciales y el xml en formato base64
                     * response = cliente_timbrar.timbrar_cfdi("AAA010101000", "h6584D56fVdBbSmmnB", codificado);
                     *
                     */}
            }
        }
コード例 #11
0
 public Validacion()
 {
     cadenaOriginal = "";
     Sello          = new SelloDigital();
     xslt1          = new XslTransform();
 }
コード例 #12
0
ファイル: XML.cs プロジェクト: jorgecb/algunproyecto
        public XML(BaseDatos baseDatos)
        {
            _baseDatos            = baseDatos;
            _selloDigital         = new SelloDigital();
            _ws                   = new WSCFDBuilderPlus();
            _xslCompiledTransform = new XslCompiledTransform();

            _facturaRutaCer = ObtenerConfiguracionSistema("FacturaRutaCer");
            if (string.IsNullOrWhiteSpace(_facturaRutaCer))
            {
                throw new ArgumentNullException("FacturaRutaCer, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaKey = ObtenerConfiguracionSistema("FacturaRutaKey");
            if (string.IsNullOrWhiteSpace(_facturaRutaKey))
            {
                throw new ArgumentNullException("FacturaRutaKey, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaFiel = ObtenerConfiguracionSistema("FacturaRutaFiel");
            if (string.IsNullOrWhiteSpace(_facturaFiel))
            {
                throw new ArgumentNullException("FacturaRutaFiel, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaXslt = ObtenerConfiguracionSistema("FacturaRutaXslt");
            if (string.IsNullOrWhiteSpace(_facturaRutaXslt))
            {
                throw new ArgumentNullException("FacturaRutaXslt, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaTimbrado = ObtenerConfiguracionSistema("FacturaRutaTimbrado");
            if (string.IsNullOrWhiteSpace(_facturaRutaTimbrado))
            {
                throw new ArgumentNullException("FacturaRutaTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsUrlTimbrado = ObtenerConfiguracionSistema("WsUrlTimbrado");
            if (string.IsNullOrWhiteSpace(_wsUrlTimbrado))
            {
                throw new ArgumentNullException("WsUrlTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsUsuarioTimbrado = ObtenerConfiguracionSistema("WsUsuarioTimbrado");
            if (string.IsNullOrWhiteSpace(_wsUsuarioTimbrado))
            {
                throw new ArgumentNullException("WsUsuarioTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsContraseñaTimbrado = ObtenerConfiguracionSistema("WsContraseñaTimbrado");
            if (string.IsNullOrWhiteSpace(_wsContraseñaTimbrado))
            {
                throw new ArgumentNullException("WsContraseñaTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaCertificado = ObtenerCertificado();
            if (string.IsNullOrWhiteSpace(_facturaCertificado))
            {
                throw new ArgumentNullException("FacturaCertificado, no se encontró archivo .cer en la ruta " + _facturaRutaCer);
            }

            _facturaArchivoKey = ObtenerFacturaArchivoKey();
            if (_facturaArchivoKey == null)
            {
                throw new ArgumentNullException("FacturaArchivoKey,  no se encontró archivo .key en la ruta " + _facturaRutaKey);
            }

            if (!File.Exists(_facturaRutaXslt))
            {
                throw new ArgumentNullException("FacturaRutaXslt,  no se encontró archivo .xslt en la ruta " + _facturaRutaXslt);
            }

            _xslCompiledTransform.Load(_facturaRutaXslt);
        }
コード例 #13
0
        public List <CFDIEmpleado> generaComprobanteV33(TipoNomina tipoNomina, PeriodosNomina periodosNomina, List <CFDIEmpleado> listCFDIEmpleados, ConfiguraTimbrado configuraTimbrado, System.Xml.Xsl.XslCompiledTransform transformerCadenaOriginal, DBContextAdapter dbContextSimple)
        {
            Comprobante oComprobante = new Comprobante();
            //aqui va que agarre el certificado de donde se tiene configurado
            ConcepNomDefi conceptoNominaSubsidio = servicioCFDIEmpleado.getConceptoNominaSubsidio(dbContextSimple);

            /* string pathCer = ruta;
             * string pathKey = ruta;*/
            string pathXML = ruta;
            // string clavePrivada = null;
            SelloDigital oSelloDigital     = new SelloDigital();
            Certificados certificadoActual = new Certificados();


            listCFDIEmpleados = listCFDIEmpleados == null ? new List <CFDIEmpleado>() : listCFDIEmpleados;
            List <object> timbreFiscalDigitales;

            try
            {
                List <DatosEmpleadoComprobate> datosEmpleadoComprobates = new List <DatosEmpleadoComprobate>();
                if (listCFDIEmpleados.Count > 0)
                {
                    RazonesSociales razonSocial = listCFDIEmpleados[0].razonesSociales;
                    int             i, j;
                    String          nombreFile;
                    certificadoActual = servicioCertificado.certificadoActualId(razonSocial.id, dbContextSimple);


                    StringBuilder pathXmlExistentes = new StringBuilder();
                    pathXmlExistentes.Append(construyeRutaXML(razonSocial, tipoNomina, periodosNomina)).Append(System.IO.Path.DirectorySeparatorChar);
                    /*******************Busca documentos ya existentes********************/
                    Comprobante comprobanteExistentes;
                    ConstruyeTimbreFiscalDigital11 timbreDigitalCadenaOrig = null;
                    List <CFDIEmpleado>            listCFDIEmpleadosTimbrados = new List <CFDIEmpleado>();
                    String ruta2 = pathXmlExistentes.ToString(), nombreArchivo;
                    for (i = 0; i < listCFDIEmpleados.Count(); i++)
                    {
                        nombreArchivo = nomenclaturaNombreArchivo(tipoNomina, periodosNomina, listCFDIEmpleados[i]);

                        if (listCFDIEmpleados[i].cfdiRecibo.statusTimbrado == StatusTimbrado.TIMBRADO)
                        {
                            XmlDocument  doc = new XmlDocument();
                            MemoryStream ms  = new MemoryStream(listCFDIEmpleados[i].cfdiRecibo.xmlTimbrado);
                            doc.Load(ms);
                            XmlSerializer oXmlSerializar = new XmlSerializer(typeof(Comprobante));
                            using (XmlReader writer = new XmlNodeReader(doc))
                            {
                                comprobanteExistentes = (Comprobante)oXmlSerializar.Deserialize(writer);
                            }

                            CreateXML(comprobanteExistentes, string.Concat(ruta2, nombreArchivo));
                            listCFDIEmpleadosTimbrados.Add(listCFDIEmpleados[i]);
                        }
                    }

                    if (listCFDIEmpleadosTimbrados.Count() > 0)
                    {
                        for (i = 0; i < listCFDIEmpleadosTimbrados.Count; i++)
                        {
                            listCFDIEmpleados.Remove(listCFDIEmpleadosTimbrados[i]);
                        }
                    }

                    Comprobante       comprobante = null;
                    ConstruyeNomina12 creaXmlNomina = new ConstruyeNomina12();
                    Nomina            nomina12;

                    if (listCFDIEmpleados.Count > 0)
                    {
                        for (i = 0; i < listCFDIEmpleados.Count; i++)
                        {
                            if (listCFDIEmpleados[i].cfdiRecibo.statusXmlSat == StatusXmlSat.NINGUNO)
                            {
                                listCFDIEmpleados[i].certificadoAsignado = certificadoActual;
                                comprobante = construyeComprobante(listCFDIEmpleados[i]);
                                listCFDIEmpleados[i].cfdiRecibo.fechaEmision = fechaGeneraXML;
                                nomina12 = creaXmlNomina.generaComplementoNomina(listCFDIEmpleados[i], conceptoNominaSubsidio);
                                if (creaXmlNomina.mensajeNomina.noError > 0)
                                {
                                    DatosEmpleadoComprobate errorNominaDatos = new DatosEmpleadoComprobate(listCFDIEmpleados[i], comprobante);
                                    datosEmpleadoComprobates.Add(new DatosEmpleadoComprobate(listCFDIEmpleados[i], comprobante));
                                    errorNominaDatos.cfdiEmpleado.mensaje = creaXmlNomina.mensajeNomina.error;
                                }
                                else
                                {
                                    comprobante = agregarComplementoNomina(comprobante, nomina12);
                                    datosEmpleadoComprobates.Add(new DatosEmpleadoComprobate(listCFDIEmpleados[i], comprobante));
                                }
                            }
                            else if (listCFDIEmpleados[i].cfdiRecibo.statusXmlSat == StatusXmlSat.ENVIADO_SAT)
                            {
                                try
                                {
                                    XmlDocument  doc = new XmlDocument();
                                    MemoryStream ms  = new MemoryStream(listCFDIEmpleados[i].cfdiRecibo.xmlTimbrado);
                                    doc.Load(ms);
                                    XmlSerializer oXmlSerializar = new XmlSerializer(typeof(Comprobante));
                                    using (XmlReader writer = new XmlNodeReader(doc))
                                    {
                                        comprobante = (Comprobante)oXmlSerializar.Deserialize(writer);
                                    }
                                }
                                catch (Exception)
                                {
                                    listCFDIEmpleados[i].certificadoAsignado     = certificadoActual;
                                    listCFDIEmpleados[i].cfdiRecibo.statusXmlSat = StatusXmlSat.NINGUNO;
                                    comprobante = construyeComprobante(listCFDIEmpleados[i]);
                                    listCFDIEmpleados[i].cfdiRecibo.fechaEmision = fechaGeneraXML;
                                    nomina12    = creaXmlNomina.generaComplementoNomina(listCFDIEmpleados[i], conceptoNominaSubsidio);
                                    comprobante = agregarComplementoNomina(comprobante, nomina12);
                                }
                                datosEmpleadoComprobates.Add(new DatosEmpleadoComprobate(listCFDIEmpleados[i], comprobante));
                            }
                        }
                        CFDIRecibo recibo;
                        for (i = 0; i < datosEmpleadoComprobates.Count; i++)
                        {
                            if (datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.statusXmlSat == StatusXmlSat.NINGUNO)
                            {
                                nombreFile = nomenclaturaNombreArchivo(tipoNomina, periodosNomina, datosEmpleadoComprobates[i].cfdiEmpleado);
                                CreateXML(datosEmpleadoComprobates[i].comprobante, string.Concat(ruta2, nombreFile));
                                string cadenaOriginal = getCadenaoriginal(string.Concat(ruta2, nombreFile));


                                //byte[] ClavePrivada1 = razonSocial.llaveSAT;
                                byte[] ClavePrivada1 = certificadoActual.llavePrivada;
                                datosEmpleadoComprobates[i].comprobante.Sello = oSelloDigital.Sellar(cadenaOriginal, ClavePrivada1, certificadoActual.password);
                                CreateXML(datosEmpleadoComprobates[i].comprobante, string.Concat(ruta2, nombreFile));
                                recibo                   = datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo;
                                recibo.total             = Convert.ToDouble(datosEmpleadoComprobates[i].comprobante.Total);
                                recibo.folioCFDI         = datosEmpleadoComprobates[i].comprobante.Folio;
                                recibo.noCertificado     = datosEmpleadoComprobates[i].comprobante.NoCertificado;
                                recibo.sello             = (datosEmpleadoComprobates[i].comprobante.Sello);
                                recibo.serieCFDI         = (datosEmpleadoComprobates[i].comprobante.Serie);
                                recibo.cadenaCertificado = (datosEmpleadoComprobates[i].comprobante.Certificado);
                                recibo.version           = (datosEmpleadoComprobates[i].comprobante.Version);
                                recibo.serie             = (datosEmpleadoComprobates[i].comprobante.Serie);

                                datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo = (recibo);

                                datosEmpleadoComprobates[i].archivoByte   = System.IO.File.ReadAllBytes(string.Concat(ruta2, nombreFile));
                                datosEmpleadoComprobates[i].nombreArchivo = nombreFile;
                            }
                            else if (datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.statusXmlSat == StatusXmlSat.ENVIADO_SAT)
                            {
                                nombreFile = nomenclaturaNombreArchivo(tipoNomina, periodosNomina, datosEmpleadoComprobates[i].cfdiEmpleado);
                                datosEmpleadoComprobates[i].archivoByte   = datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.xmlTimbrado;
                                datosEmpleadoComprobates[i].nombreArchivo = nombreFile;
                            }
                        }

                        List <InfoExtra> infoExtras = new List <InfoExtra>();
                        InfoExtra        infoExtra;

                        for (i = 0; i < datosEmpleadoComprobates.Count; i++)
                        {
                            datosEmpleadoComprobates[i].statusTimbrado = (StatusTimbrado.EN_PROCESO);
                            infoExtra = new InfoExtra();

                            infoExtra.archivoXML    = (datosEmpleadoComprobates[i].archivoByte);
                            infoExtra.nombreArchivo = (datosEmpleadoComprobates[i].nombreArchivo);
                            infoExtra.rfcEmisor     = (datosEmpleadoComprobates[i].comprobante.Emisor.Rfc);
                            infoExtra.rfcReceptor   = (datosEmpleadoComprobates[i].comprobante.Receptor.Rfc);
                            infoExtra.version       = (datosEmpleadoComprobates[i].comprobante.Version);
                            infoExtra.folio         = (datosEmpleadoComprobates[i].comprobante.Folio);
                            infoExtras.Add(infoExtra);
                            if (datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.statusXmlSat == StatusXmlSat.NINGUNO)
                            {
                                datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.statusXmlSat = (StatusXmlSat.ENVIADO_SAT);
                                datosEmpleadoComprobates[i].cfdiEmpleado.cfdiRecibo.xmlTimbrado  = (datosEmpleadoComprobates[i].archivoByte);
                                if (datosEmpleadoComprobates[i].cfdiEmpleado.id != 0)
                                {
                                    servicioCFDIEmpleado.actualizar(datosEmpleadoComprobates[i].cfdiEmpleado, dbContextSimple);
                                }
                            }
                        }

                        //timbrar
                        if (infoExtras.Count > 0)
                        {
                            //datos de timbrar desde la razon social
                            TimbrarXmlSat timbrarXmlSat = new TimbrarXmlSat();
                            InfoATimbrar  infoATimbrar  = new InfoATimbrar();
                            infoATimbrar.tipoOperacion  = (TipoOperacionWS.TIMBRAR);
                            infoATimbrar.infoExtras     = (infoExtras);
                            infoATimbrar.password       = configuraTimbrado.contraseña;
                            infoATimbrar.urlWebServices = configuraTimbrado.URL;
                            infoATimbrar.usuario        = configuraTimbrado.usuario;

                            timbreFiscalDigitales = timbrarXmlSat.generaTimbres(infoATimbrar, dbContextSimple);
                            if (timbrarXmlSat.error != null)
                            {
                                mensaje.noError   = 101;
                                mensaje.resultado = (timbrarXmlSat.error);
                                if (timbreFiscalDigitales.Count > 0)
                                {
                                    for (i = 0; i < timbreFiscalDigitales.Count; i++)
                                    {
                                        j = 0;
                                        DatosTimbreFiscalDigital info = (DatosTimbreFiscalDigital)timbreFiscalDigitales[i];

                                        while (j < datosEmpleadoComprobates.Count)
                                        {
                                            if (info.error != 0)
                                            {
                                                if (string.Equals((datosEmpleadoComprobates[j].folio == null ? "" : datosEmpleadoComprobates[j].folio), (info.folio == null ? "" : info.folio), StringComparison.OrdinalIgnoreCase))
                                                {
                                                    datosEmpleadoComprobates[j].cfdiEmpleado.mensaje = info.descripcion;
                                                }
                                            }

                                            j++;
                                        }
                                    }
                                }
                            }
                            timbreFiscalDigitales = timbreFiscalDigitales == null ? new List <object>() : timbreFiscalDigitales;

                            if (timbreFiscalDigitales.Count > 0)
                            {
                                XmlNode tfd;
                                ConstruyeTimbreFiscalDigital11 digital11 = new ConstruyeTimbreFiscalDigital11(ruta);

                                j = 0;
                                listCFDIEmpleados.Clear();
                                for (i = 0; i < timbreFiscalDigitales.Count; i++)
                                {
                                    while (j < datosEmpleadoComprobates.Count)
                                    {
                                        DatosTimbreFiscalDigital timbre = (DatosTimbreFiscalDigital)timbreFiscalDigitales[i];


                                        if (string.Equals((datosEmpleadoComprobates[j].folio == null ? "" : datosEmpleadoComprobates[j].folio), (timbre.folio == null ? "" : timbre.folio), StringComparison.OrdinalIgnoreCase))
                                        {
                                            if (string.Equals(timbre.status, "200", StringComparison.OrdinalIgnoreCase) || string.Equals(timbre.status, "307", StringComparison.OrdinalIgnoreCase))
                                            {
                                                //CreateXMLTimbreFiscal(digital11.contruyeTimbreFiscalDigital(timbreFiscalDigitales[i]), string.Concat(ruta2, "pruebaTimbre.xml"));

                                                recibo = datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo;
                                                CreateXML(datosEmpleadoComprobates[j].comprobante, string.Concat(ruta2, datosEmpleadoComprobates[j].nombreArchivo));
                                                string cadenaOriginal = getCadenaoriginal(string.Concat(ruta2, datosEmpleadoComprobates[j].nombreArchivo));
                                                recibo.cadenaCertificado   = cadenaOriginal;
                                                recibo.certificadoTimbrado = (timbre.noCertificadoSAT);
                                                recibo.noCertificadoSAT    = (timbre.noCertificadoSAT);
                                                recibo.fechaHoraTimbrado   = (timbre.fechaTimbrado);
                                                recibo.selloTimbrado       = (timbre.selloSAT);
                                                recibo.selloSAT            = (timbre.selloSAT);
                                                recibo.UUID           = (timbre.uuid);
                                                recibo.rfcProvCertif  = (timbre.referenciasProveedor);
                                                recibo.statusTimbrado = (StatusTimbrado.TIMBRADO);
                                                recibo.statusXmlSat   = (StatusXmlSat.RECIBIDO_SAT);
                                                recibo.xmlTimbrado    = (timbre.xmlTimbrado);


                                                string cadenaOriginalSAT1 = "||" + timbre.version + "|" + timbre.uuid + "|" + timbre.fechaTimbrado + "|" + timbre.referenciasProveedor;
                                                if (timbre.descripcion != "")
                                                {
                                                    cadenaOriginalSAT1 += "|" + timbre.descripcion + "|" + timbre.selloCFD + "|" + timbre.noCertificadoSAT + "||";
                                                }
                                                else
                                                {
                                                    cadenaOriginalSAT1 += "|" + timbre.selloCFD + "|" + timbre.noCertificadoSAT + "||";
                                                }

                                                recibo.cadenaOriginalTimbrado = cadenaOriginalSAT1;


                                                datosEmpleadoComprobates[j].cfdiEmpleado.recienTimbrado = (true);
                                                datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo     = (recibo);



                                                if (datosEmpleadoComprobates[i].cfdiEmpleado.id != 0)
                                                {
                                                    servicioCFDIEmpleado.actualizar(datosEmpleadoComprobates[j].cfdiEmpleado, dbContextSimple);
                                                }
                                            }
                                            else
                                            {
                                                datosEmpleadoComprobates[j].statusTimbrado = StatusTimbrado.ERROR;
                                                datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo.mensajeRec = (timbre.descripcion);

                                                datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo.statusTimbrado = StatusTimbrado.ERROR;
                                                datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo.statusXmlSat   = StatusXmlSat.NINGUNO;
                                                datosEmpleadoComprobates[j].cfdiEmpleado.cfdiRecibo.xmlTimbrado    = null;
                                                if (datosEmpleadoComprobates[j].cfdiEmpleado.id != 0)
                                                {
                                                    servicioCFDIEmpleado.actualizar(datosEmpleadoComprobates[j].cfdiEmpleado, dbContextSimple);
                                                }
                                            }

                                            datosEmpleadoComprobates[j].cfdiEmpleado.mensaje = (timbre.descripcion);
                                            listCFDIEmpleados.Add(datosEmpleadoComprobates[j].cfdiEmpleado);
                                            // datosEmpleadoComprobates.RemoveAt(j);
                                            j = 0;
                                            break;
                                        }

                                        else
                                        {
                                            j++;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (listCFDIEmpleadosTimbrados.Count() > 0)
                    {
                        listCFDIEmpleados.AddRange(listCFDIEmpleadosTimbrados);
                        //                    Utilerias.ordena(listCFDIEmpleados, uuidCxn);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }


            return(listCFDIEmpleados);
        }
コード例 #14
0
 private void xml2()
 {
     Models.Configuration configuracion = new Models.Configuration();
     Models.Client        clientes      = new Models.Client();
     Models.Product       productos     = new Models.Product();
     using (configuracion)
     {
         using (clientes)
         {
             using (productos)
             {
                 List <Models.Configuration> config = configuracion.getConfiguration();
                 DateTime            dt             = DateTime.Now;
                 DateTime            x            = Convert.ToDateTime(String.Format("{0:s}", dt));
                 Comprobante         oComprobante = new Comprobante();
                 ComprobanteEmisor   oEmisor      = new ComprobanteEmisor();
                 ComprobanteReceptor oReceptor    = new ComprobanteReceptor();
                 string username = "******";
                 string password = "******";
                 string CertFile = config[0].Cer;
                 string KeyFile = config[0].Key;
                 string KeyPass = config[0].Pass;
                 string Errores = "";
                 string noCertificado, aa, b, c;
                 SelloDigital.leerCER(CertFile, out aa, out b, out c, out noCertificado);
                 oComprobante.Folio             = txtFolio.Text;
                 oComprobante.Version           = "3.3";
                 oComprobante.Fecha             = x.ToString("yyyy-MM-ddTHH:mm:ss");
                 oComprobante.Serie             = "A";
                 oComprobante.NoCertificado     = noCertificado;
                 oComprobante.SubTotal          = Convert.ToDecimal(DoFormat(Convert.ToDouble(txtSubtotal.Text)));
                 oComprobante.Moneda            = "MXN";
                 oComprobante.Total             = Convert.ToDecimal(DoFormat(Convert.ToDouble(txtSubtotal.Text)));
                 oComprobante.TipoDeComprobante = "I";
                 oComprobante.FormaPago         = txtFpago.Text;
                 oComprobante.CondicionesDePago = "CONTADO";
                 oComprobante.MetodoPago        = txtMPago.Text;
                 oComprobante.LugarExpedicion   = config[0].Cp;
                 oEmisor.Rfc           = config[0].RFC;
                 oEmisor.Nombre        = config[0].Razon_social;
                 oEmisor.RegimenFiscal = config[0].Regimen;
                 List <Models.Client> cliente                             = clientes.getClientbyId(Convert.ToInt16(txtIdCliente.Text));
                 oReceptor.Rfc         = cliente[0].RFC;
                 oReceptor.UsoCFDI     = txtUsoCfdi.Text;
                 oReceptor.Nombre      = txtCliente.Text;
                 oComprobante.Emisor   = oEmisor;
                 oComprobante.Receptor = oReceptor;
                 List <Models.Product>      producto                      = null;
                 List <ComprobanteConcepto> lstConceptos                  = new List <ComprobanteConcepto>();
                 foreach (DataGridViewRow row in dtProductos.Rows)
                 {
                     ComprobanteConcepto oConcepto = new ComprobanteConcepto();
                     producto = productos.getProductById(Convert.ToInt16(row.Cells["id_producto"].Value.ToString()));
                     List <ComprobanteConceptoImpuestosTraslado> Ltraslados  = new List <ComprobanteConceptoImpuestosTraslado>();
                     ComprobanteConceptoImpuestos         oConoceptoimpuesto = new ComprobanteConceptoImpuestos();
                     ComprobanteConceptoImpuestosTraslado oConcepto_traslado = new ComprobanteConceptoImpuestosTraslado();
                     oConcepto.ClaveProdServ = producto[0].Code_sat;
                     oConcepto.Cantidad      = Convert.ToDecimal(row.Cells["cantidad"].Value.ToString());
                     oConcepto.ClaveUnidad   = producto[0].Medida_sat;
                     oConcepto.Descripcion   = row.Cells["descripcion"].Value.ToString();
                     oConcepto.ValorUnitario = Convert.ToDecimal(DoFormat(Convert.ToDouble(row.Cells["pu"].Value.ToString())));
                     oConcepto.Importe       = Convert.ToDecimal(DoFormat(Convert.ToDouble(row.Cells["total"].Value.ToString())));
                     //oConcepto.Descuento = Convert.ToDecimal(0);
                     oConcepto.Unidad                       = "PIEZA";
                     oConcepto.NoIdentificacion             = producto[0].Code1;
                     oConcepto_traslado.Base                = Convert.ToDecimal(DoFormat(Convert.ToDouble(row.Cells["total"].Value.ToString())));
                     oConcepto_traslado.Impuesto            = "002";
                     oConcepto_traslado.TipoFactor          = "Tasa";
                     oConcepto_traslado.TasaOCuota          = Convert.ToDecimal("0.000000");
                     oConcepto_traslado.Importe             = Convert.ToDecimal(DoFormat(Convert.ToDouble(row.Cells["total"].Value.ToString()))) * 0;
                     oConcepto_traslado.TasaOCuotaSpecified = true;
                     oConcepto_traslado.ImporteSpecified    = true;
                     Ltraslados.Add(oConcepto_traslado);
                     oConoceptoimpuesto.Traslados = Ltraslados.ToArray();
                     oConcepto.Impuestos          = oConoceptoimpuesto;
                     lstConceptos.Add(oConcepto);
                 }
                 oComprobante.Conceptos = lstConceptos.ToArray();
                 ComprobanteImpuestos                oImpuuestos          = new ComprobanteImpuestos();
                 List <ComprobanteImpuestos>         lImpuestos           = new List <ComprobanteImpuestos>();
                 ComprobanteImpuestosTraslado        oImpuestos_traslados = new ComprobanteImpuestosTraslado();
                 List <ComprobanteImpuestosTraslado> lImpuestos_traslados = new List <ComprobanteImpuestosTraslado>();
                 oImpuestos_traslados.Impuesto   = "002";
                 oImpuestos_traslados.TipoFactor = "Tasa";
                 oImpuestos_traslados.TasaOCuota = Convert.ToDecimal("0.000000");
                 oImpuestos_traslados.Importe    = Convert.ToDecimal("0.00");
                 lImpuestos_traslados.Add(oImpuestos_traslados);
                 oImpuuestos.TotalImpuestosRetenidos            = Convert.ToDecimal(0.00);
                 oImpuuestos.TotalImpuestosTrasladadosSpecified = true;
                 oImpuuestos.Traslados  = lImpuestos_traslados.ToArray();
                 oComprobante.Impuestos = oImpuuestos;
                 xml(oComprobante, config[0].Ruta_factura + txtFolio.Text + ".xml");
                 string CadenaOriginal                                    = "";
                 string path_cad                                          = @"XSLT\cadenaoriginal_3_3.xslt";
                 System.Xml.Xsl.XslCompiledTransform transformador        = new System.Xml.Xsl.XslCompiledTransform(true);
                 transformador.Load(path_cad);
                 using (StringWriter sw = new StringWriter())
                 {
                     using (XmlWriter xwo = XmlWriter.Create(sw, transformador.OutputSettings))
                     {
                         transformador.Transform(config[0].Ruta_factura + txtFolio.Text + ".xml", xwo);
                         CadenaOriginal = sw.ToString();
                     }
                 }
                 SelloDigital sellodigital = new SelloDigital();
                 oComprobante.Certificado = sellodigital.Certificado(CertFile);
                 oComprobante.Sello       = sellodigital.Sellar(CadenaOriginal, KeyFile, KeyPass);
                 xml(oComprobante, config[0].Ruta_factura + txtFolio.Text + ".xml");
                 timbrar();
             }
         }
     }
 }
コード例 #15
0
ファイル: CFDI.cs プロジェクト: gultekincenter/PointOfSale-3
        public bool Facturar()
        {
            Inicializar();
            if (Venta == null || partidas.Count == 0 || empresa == null || cliente == null)
            {
                Ambiente.Mensaje("Venta || partidas || empresa || Cliente == null");
                return(false);
            }

            if (cliente.Rfc == null)
            {
                Ambiente.Mensaje("PROCESO ABORTADO, RFC DEL CLIENTE NO ES VÁLIDO");
                return(false);
            }

            if (cliente.Rfc.Trim().Length == 0)
            {
                Ambiente.Mensaje("PROCESO ABORTADO, RFC DEL CLIENTE NO ES VÁLIDO");
                return(false);
            }

            SelloDigital.leerCER(empresa.RutaCer, out string a, out string b, out string c, out string NoCer);
            noCertificado = NoCer;

            //Encabezado
            comprobante.Version       = "3.3";
            comprobante.Serie         = "F";
            comprobante.Folio         = Venta.NoRef.ToString();
            comprobante.Fecha         = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
            comprobante.FormaPago     = Venta.FormaPago1;
            comprobante.NoCertificado = noCertificado;
            comprobante.SubTotal      = Math.Round(Venta.SubTotal, 2);
            //comprobante.Descuento = 0;
            comprobante.Moneda            = "MXN";
            comprobante.Total             = Math.Round(Venta.Total, 2);
            comprobante.TipoDeComprobante = Venta.TipoComprobante;
            comprobante.MetodoPago        = Venta.MetodoPago;
            comprobante.LugarExpedicion   = empresa.Cp;

            //Emisor
            emisor.Rfc           = empresa.Rfc;
            emisor.Nombre        = empresa.RazonSocial;
            emisor.RegimenFiscal = empresa.RegimenFiscalId;

            //Receptor
            receptor.Nombre  = cliente.RazonSocial;
            receptor.Rfc     = cliente.Rfc;
            receptor.UsoCFDI = cliente.UsoCfdiid;

            //Asignar emisor y receptor al comprobante
            comprobante.Emisor   = emisor;
            comprobante.Receptor = receptor;

            //Agregar los conceptos
            totalIeps = 0;
            totalIva  = 0;
            /**********************************CONCEPTOS********************************/

            foreach (var p in partidas)
            {
                concepto          = new ComprobanteConcepto();
                impuestosConcepto = new List <ComprobanteConceptoImpuestosTraslado>();


                concepto.ClaveProdServ = "01010101";

                if (Venta.EsFacturaGlobal)
                {
                    concepto.ClaveUnidad = "ACT";
                }
                else
                {
                    concepto.ClaveUnidad = "H87";
                }

                //concepto.ClaveUnidad = p.ClaveUnidad;
                //concepto.ClaveProdServ = p.ClaveProdServ;
                concepto.Descripcion   = p.Descripcion;
                concepto.Cantidad      = p.Cantidad;
                concepto.ValorUnitario = p.Precio;
                concepto.Importe       = p.SubTotal;


                //Llenado del impuesto
                if (p.ImporteImpuesto1 == 0 && p.ImporteImpuesto2 == 0)
                {
                    /*EXCENTO DE IMPUESTOS (IVA EXCENTO)*/
                    ivaConcepto            = new ComprobanteConceptoImpuestosTraslado();
                    ivaConcepto.Base       = p.SubTotal;
                    ivaConcepto.Impuesto   = p.ClaveImpuesto1;
                    ivaConcepto.TipoFactor = "Exento";
                    impuestosConcepto.Add(ivaConcepto);
                }
                else if (p.ImporteImpuesto1 == 0 && p.ImporteImpuesto2 > 0)
                {
                    /*SOLO IEPS*/
                    iepsConcepto            = new ComprobanteConceptoImpuestosTraslado();
                    iepsConcepto.Base       = p.SubTotal;
                    iepsConcepto.TasaOCuota = p.Impuesto2;
                    iepsConcepto.TipoFactor = p.TasaOcuota2;
                    iepsConcepto.Impuesto   = p.ClaveImpuesto2;
                    iepsConcepto.Importe    = p.ImporteImpuesto2;
                    impuestosConcepto.Add(iepsConcepto);
                    totalIeps += p.ImporteImpuesto2;
                }
                else if (p.ImporteImpuesto1 > 0 && p.ImporteImpuesto2 == 0)
                {
                    /*SOLO IVA*/
                    ivaConcepto            = new ComprobanteConceptoImpuestosTraslado();
                    ivaConcepto.Base       = p.SubTotal;
                    ivaConcepto.TasaOCuota = p.Impuesto1;
                    ivaConcepto.TipoFactor = p.TasaOcuota1;
                    ivaConcepto.Impuesto   = p.ClaveImpuesto1;
                    ivaConcepto.Importe    = p.ImporteImpuesto1;
                    impuestosConcepto.Add(ivaConcepto);
                    totalIva += p.ImporteImpuesto1;
                }
                else if (p.ImporteImpuesto1 > 0 && p.ImporteImpuesto2 > 0)
                {
                    /*IVA + IEPS*/
                    ivaConcepto            = new ComprobanteConceptoImpuestosTraslado();
                    ivaConcepto.Base       = p.SubTotal;
                    ivaConcepto.TasaOCuota = p.Impuesto1;
                    ivaConcepto.TipoFactor = p.TasaOcuota1;
                    ivaConcepto.Impuesto   = p.ClaveImpuesto1;
                    ivaConcepto.Importe    = p.ImporteImpuesto1;
                    impuestosConcepto.Add(ivaConcepto);
                    totalIva += p.ImporteImpuesto1;

                    iepsConcepto            = new ComprobanteConceptoImpuestosTraslado();
                    iepsConcepto.Base       = p.SubTotal;
                    iepsConcepto.TasaOCuota = p.Impuesto2;
                    iepsConcepto.TipoFactor = p.TasaOcuota2;
                    iepsConcepto.Impuesto   = p.ClaveImpuesto2;
                    iepsConcepto.Importe    = p.ImporteImpuesto2;
                    impuestosConcepto.Add(iepsConcepto);
                    totalIeps += p.ImporteImpuesto2;
                }

                //Agregar los impuestos del concepto al concepto y agregar el concepto a la lista//
                concepto.Impuestos           = new ComprobanteConceptoImpuestos();
                concepto.Impuestos.Traslados = impuestosConcepto.ToArray();
                conceptos.Add(concepto);
            }

            /***************************************************************************/
            /********************Operaciones a nivel del comprobante********************/
            comprobante.Conceptos     = conceptos.ToArray();
            totalImpuestosComprobante = new ComprobanteImpuestos();
            impuestosComprobante      = new List <ComprobanteImpuestosTraslado>();
            ivaComprobante            = new ComprobanteImpuestosTraslado();
            iepsComprobante           = new ComprobanteImpuestosTraslado();

            if (totalIva > 0)
            {
                //Total IVA
                ivaComprobante.Importe    = totalIva;
                ivaComprobante.Impuesto   = "002";
                ivaComprobante.TipoFactor = "Tasa";
                ivaComprobante.TasaOCuota = 0.160000m;
                impuestosComprobante.Add(ivaComprobante);
            }

            if (totalIeps > 0)
            {
                //Total IEPS
                iepsComprobante.Importe    = totalIeps;
                iepsComprobante.Impuesto   = "003";
                iepsComprobante.TipoFactor = "Tasa";
                iepsComprobante.TasaOCuota = 0.080000m;
                impuestosComprobante.Add(iepsComprobante);
            }


            if ((totalIva + totalIeps) > 0)
            {
                //Total impuestos trasladados
                totalImpuestosComprobante.TotalImpuestosTrasladados = Math.Round(totalIva + totalIeps, 2);
                totalImpuestosComprobante.Traslados = impuestosComprobante.ToArray();
                comprobante.Impuestos = totalImpuestosComprobante;
            }


            /***************************************************************************/
            facturaActual = empresa.DirectorioComprobantes + "FACTURA " + Venta.NoRef.ToString() + "_" + Venta.CreatedBy + "_" + Ambiente.TimeText(Venta.CreatedAt) + ".XML";


            //Crear Xml
            Serializar(comprobante);
            cadenaOriginal          = GetCadenaOriginal();
            comprobante.Certificado = selloDigital.Certificado(empresa.RutaCer);
            comprobante.Sello       = selloDigital.Sellar(cadenaOriginal, empresa.RutaKey, empresa.ClavePrivada);
            Serializar(comprobante);
            return(Timbrar(facturaActual));
        }