Beispiel #1
0
        public string RecepcionArchivos(string pathDocumento, string urlDocumeto, string nombreArchivo, string PathServer)
        {
            //string PathServer = @"C:\Users\Public\Documents\ArchivosXml";
            _URLWS = urlDocumeto;
            byte[] bytes     = File.ReadAllBytes(pathDocumento);
            object RESULTADO = "";

            //convertir el archivo en formato 64 bytes
            RESULTADO = Convert.ToBase64String(bytes);
            HttpWebRequest request         = CreateWebRequest();
            XmlDocument    soapEnvelopeXml = new XmlDocument();

            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ec=""http://ec.gob.sri.ws.recepcion"">
                <soapenv:Header/>
                    <soapenv:Body>
                        <ec:validarComprobante>
                            <!--Optional:-->
                            <xml>" + RESULTADO + "</xml>" +
                                    "</ec:validarComprobante>" +
                                    "</soapenv:Body>" +
                                    "</soapenv:Envelope>");
            string soapResult = "";

            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    soapEnvelopeXml.Save(stream);
                }
                try
                {
                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                        {
                            _xmlResutado = rd.ReadToEnd();
                        }
                    }
                }
                catch (Exception ex)
                {
                    soapResult = "Error en enviar al SRI" + ex.Message;

                    RecepcionArchivos(pathDocumento, urlDocumeto, nombreArchivo, PathServer);
                }
            }
            catch (Exception x)
            {
                soapResult = "Error en enviar al SRI" + x.Message;
            }
            string estado = "";

            try
            {
                XmlDocument docxml = new XmlDocument();
                docxml.Load(pathDocumento);

                XmlDocument docxml1 = new XmlDocument();
                docxml1.LoadXml(_xmlResutado);
                estado = docxml1.GetElementsByTagName("estado")[0].InnerText;
                //Preguntar sobre el directorio

                if (estado == "RECIBIDA")
                {
                    if (!Directory.Exists(PathServer + @"\Recibidos\"))
                    {
                        Directory.CreateDirectory(PathServer + @"\Recibidos\");
                    }
                    docxml.Save(@PathServer + @"\Recibidos\" + nombreArchivo + ".xml");
                }
                else
                {
                    //string CodigoError = docxml1.GetElementsByTagName("identificador")[0].InnerText;
                    // string mensaje = docxml1.GetElementsByTagName("mensaje")[0].InnerText + "-" + docxml1.GetElementsByTagName("informacionAdicional")[0].InnerText;
                    if (!Directory.Exists(PathServer + @"\Devueltos\"))
                    {
                        Directory.CreateDirectory(PathServer + @"\Devueltos\");
                    }
                    docxml1.Save(PathServer + @"\Devueltos\" + nombreArchivo + ".xml");

                    string rutaNAT = @PathServer + @"\Devueltos\";

                    string fechafinal   = Funcion.reemplazarcaracterFecha(DateTime.Now.Date.ToShortDateString());
                    String CODIERROR    = docxml1.GetElementsByTagName("identificador")[0].InnerText;
                    string mensajeerror = docxml1.GetElementsByTagName("mensaje")[1].InnerText;
                    objConsultas.EjecutarSQL("INSERT INTO [dbo].[TbErroresDocEnviados]([NombreXML],[Ruta],[FechaEmision] ,[EstadoError],[CodigoError],[MensajeError])" +
                                             "VALUES ('" + nombreArchivo + "','" + rutaNAT + "','" + fechafinal + "','" + 1 + "','" + CODIERROR + "','" + mensajeerror + "')");
                    //MessageBox.Show("Estado: " + estado + "\nClave Acceso: " + nombreArchivo + "\nError: " + mensaje);
                }


                if (!Directory.Exists(PathServer + @"\Enviados\"))
                {
                    Directory.CreateDirectory(PathServer + @"\Enviados\");
                }



                docxml.Save(@PathServer + @"\Enviados\" + @"\" + nombreArchivo + ".xml");
            }
            catch (Exception)
            {
                //throw;
            }



            return(estado);
        }
Beispiel #2
0
        public bool FormarXml()
        {
            try
            {
                fecha           = Funcion.reemplazarcaracterFecha(fecha);
                ConsutarFactura = objC.ConsutarFactura(fecha, claveacceso);
                if (ConsutarFactura.Count > 0)
                {
                    Xml      xml         = new Xml();
                    string[] vector      = ConsutarFactura[0].Split(';');
                    int      sucursal    = Convert.ToInt32(vector[0]);
                    int      caja        = Convert.ToInt32(vector[1]);
                    string   claveacceso = vector[3].Trim();


                    //string claveacc = myXmlDocument.GetElementsByTagName("claveAcceso")[0].InnerText;
                    string Substr           = claveacceso.Substring(0, 23);
                    string subStri2         = claveacceso.Substring(24, 24);
                    string claveAccesoNueva = Substr + "2" + subStri2;
                    claveacceso = Modulo11(claveAccesoNueva);

                    int NumeroFactura = Convert.ToInt32(vector[2]);

                    if (!Directory.Exists(PathServer + @"\Generados\"))
                    {
                        Directory.CreateDirectory(PathServer + @"\Generados\");
                    }
                    xml._crearXml(PathServer + @"\Generados\" + NombreGuardar + ".xml", "factura");
                    InfoTributaria InfoTributaria = new InfoTributaria();
                    InfoTributaria.Ambiente        = 2;
                    InfoTributaria.TipoEmision     = 1;
                    InfoTributaria.RazonSociaL     = "VEGA SOLIS SONNA JUDITH";
                    InfoTributaria.NombreComerciaL = "COMISARIATO SUPER 2";
                    InfoTributaria.RuC             = "1802114429001";
                    InfoTributaria.CodDoC          = "01";
                    InfoTributaria.EstaB           = "001";
                    InfoTributaria.PtoEmI          = caja.ToString("D3");
                    InfoTributaria.SecuenciaL      = NumeroFactura.ToString("D9");
                    InfoTributaria.DirMatriz       = "VIA GUAYAS Y ABDON CALDERON 207";
                    xml.InfoTributaria("infoTributaria", InfoTributaria, claveacceso);

                    InfoFactura infoFactura = new InfoFactura();
                    fecha = Funcion.reemplazarcaracterFechaViceversa(fecha);
                    infoFactura.FechaEmision         = fecha;
                    infoFactura.DirEstablecimiento   = "VIA GUAYAS Y ABDON CALDERON 207";
                    infoFactura.ObligadoContabilidad = "SI";
                    if (vector[4] != "9999999999999")
                    {
                        if (vector[4].Length == 10)
                        {
                            infoFactura.TipoIdentificacionComprador = "05";
                        }
                        else
                        {
                            infoFactura.TipoIdentificacionComprador = "04";
                        }
                    }
                    else
                    {
                        infoFactura.TipoIdentificacionComprador = "07";
                    }

                    infoFactura.GuiaRemision            = sucursal.ToString("D3") + "-" + caja.ToString("D3") + "-" + NumeroFactura.ToString("D9");
                    infoFactura.RazonSocialComprador    = vector[5];
                    infoFactura.IdentificacionComprador = vector[4];
                    infoFactura.DireccionComprador      = vector[6];
                    infoFactura.TotalDescuento          = "0.00";
                    infoFactura.Propina = "0.00";

                    objC = new Consultas();
                    double totalSinImpuesto = 0, ivapreci = 0, to = 0;
                    DetalleFactura = objC.DetalleFact(NumeroFactura, caja);
                    for (int j = 0; j < DetalleFactura.Count; j++)
                    {
                        totalSinImpuesto += DetalleFactura[j].Cantidad * DetalleFactura[j].Preciopublico_sin_iva;
                        if (DetalleFactura[j].Iva == 12)
                        {
                            ivapreci += ((DetalleFactura[j].Cantidad * DetalleFactura[j].Preciopublico_sin_iva) * 12) / 100;
                        }
                    }
                    to = totalSinImpuesto + ivapreci;
                    //string importeTotal= docxml.GetElementsByTagName("importeTotal")[0].InnerText;
                    infoFactura.TotalSinImpuestos = "" + totalSinImpuesto.ToString("#####0.00");
                    infoFactura.ImporteTotal      = to.ToString("#####0.00");/*totalpagar.ToString("#####0.00");*/

                    xml.infoFactura("infoFactura", infoFactura, to.ToString("#####0.00"), DetalleFactura);
                    xml.detalleFactura("detalles", DetalleFactura);
                    DetalleFactura = new List <Producto>();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #3
0
        public string AutorizacionArchivos(string sClaveAcceso, string PathServer)
        {
            string         sResult      = "";
            StringBuilder  sSoap        = new StringBuilder();
            XmlDocument    oXmlDoc      = new XmlDocument();
            HttpWebRequest oHttpRequest = null;
            StreamReader   oReader      = null;
            string         estado       = "";

            sSoap.Append("<soapenv:Envelope xmlns:soapenv=" + Convert.ToChar(34) + "http://schemas.xmlsoap.org/soap/envelope/" + Convert.ToChar(34) + " xmlns:ec=" + Convert.ToChar(34) + "http://ec.gob.sri.ws.autorizacion" + ((char)34) + "><soapenv:Header/>");
            sSoap.Append("\n	<soapenv:Body>");
            sSoap.Append("\n 		<ec:autorizacionComprobante>");
            sSoap.Append("\n 			<claveAccesoComprobante>"+ sClaveAcceso.Trim() + "</claveAccesoComprobante>");
            sSoap.Append("\n		</ec:autorizacionComprobante>");
            sSoap.Append("\n	</soapenv:Body>");
            sSoap.Append("\n</soapenv:Envelope>");

            try
            {
                oHttpRequest             = (HttpWebRequest)WebRequest.Create(this.sUrl);
                oHttpRequest.ContentType = "text/xml;action=\"" + this.sSoapAction;
                oHttpRequest.Method      = "POST";

                oXmlDoc.LoadXml(sSoap.ToString());
                oXmlDoc.Save(oHttpRequest.GetRequestStream());

                oReader      = new StreamReader(oHttpRequest.GetResponse().GetResponseStream());
                xmlResultado = oReader.ReadToEnd();

                XmlDocument docxmlSRI = new XmlDocument();
                docxmlSRI.LoadXml(xmlResultado);


                xmlResultado = WebUtility.HtmlDecode(xmlResultado);

                //Cargo a un XML
                XmlDocument docxml = new XmlDocument();

                var caracterPrincipal  = xmlResultado.IndexOf('?') - 1;
                var caracterSecundario = xmlResultado.LastIndexOf('?') + 2;
                xmlResultado = xmlResultado.Remove(caracterPrincipal, (caracterSecundario - caracterPrincipal));
                xmlResultado = "<?xml version=" + "\"1.0\"" + " encoding=" + "\"UTF-8\"" + "?>" + xmlResultado;
                docxml.LoadXml(xmlResultado);

                //Preguntar sobre el directorio
                string FechaAutorizacion = "", mensaje = "", infoadicional = "", tipo = "", claveconsultada = "", numeroAutorizacion = "", claveAcceso = "";
                estado = docxml.GetElementsByTagName("estado")[0].InnerText;
                string ambiente = docxml.GetElementsByTagName("ambiente")[0].InnerText;
                claveconsultada = docxml.GetElementsByTagName("claveAccesoConsultada")[0].InnerText;

                if (estado == "AUTORIZADO")
                {
                    numeroAutorizacion = docxml.GetElementsByTagName("numeroAutorizacion")[0].InnerText;
                    claveAcceso        = docxml.GetElementsByTagName("claveAcceso")[0].InnerText;
                    numeroAutorizacion = docxml.GetElementsByTagName("numeroAutorizacion")[0].InnerText;
                    FechaAutorizacion  = Convert.ToDateTime(docxml.GetElementsByTagName("fechaAutorizacion")[0].InnerText).ToString();

                    //formar ride si no es consumidor final
                    List <Factura> objFactura = llenarDatosEmcabezadoyPie(PathServer + @"\Generados\" + sClaveAcceso + ".xml", FechaAutorizacion, ambiente);

                    if (FormarRide)
                    {
                        List <DetalleFactura> listaDetalle = llenarDetalleFactura(PathServer + @"\Generados\" + sClaveAcceso + ".xml");
                        List <PieFactura>     listaPie     = llenarPieFactura(PathServer + @"\Generados\" + sClaveAcceso + ".xml");



                        ReportViewer objreportview = new ReportViewer();


                        objreportview.ProcessingMode = ProcessingMode.Local;

                        objreportview.LocalReport.ReportPath = PathArchivoRide;
                        String          ruta  = PathLogo;
                        ReportParameter param = new ReportParameter("RutaImg", ruta, true);
                        objreportview.LocalReport.EnableExternalImages = true;
                        objreportview.LocalReport.SetParameters(param);
                        objreportview.RefreshReport();

                        BarcodeLib.Barcode Codigo = new BarcodeLib.Barcode();
                        Codigo.IncludeLabel = true;

                        Panel obp = new Panel();
                        obp.BackgroundImage = Codigo.Encode(BarcodeLib.TYPE.CODE128, sClaveAcceso, Color.Black, Color.White, 1000, 300);
                        Image imgFinal = (Image)obp.BackgroundImage.Clone();


                        imgFinal.Save("p.png", ImageFormat.Png);

                        imgFinal.Dispose();
                        //file:\C:\Users\MaxDJ\Desktop\ModuloFacturacionElectronica\ModuloFacturacionElectronica\bin\Debug\p.png
                        String          ruta1  = PathCodigoBarra;
                        ReportParameter param2 = new ReportParameter("CodigoBarra", ruta1, true);
                        objreportview.LocalReport.EnableExternalImages = true;
                        objreportview.LocalReport.SetParameters(param2);
                        objreportview.RefreshReport();

                        objreportview.LocalReport.DataSources.Clear();
                        objreportview.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", objFactura));
                        objreportview.LocalReport.DataSources.Add(new ReportDataSource("DetalleFactura", listaDetalle));
                        objreportview.LocalReport.DataSources.Add(new ReportDataSource("PieFactura", listaPie));
                        objreportview.RefreshReport();



                        string    reportType = "PDF";
                        string    mimeType;
                        string    encoding;
                        string    fileNameExtension;
                        Warning[] warnings;
                        string[]  streams;



                        byte[] bytes = objreportview.LocalReport.Render(reportType,
                                                                        //deviceInfo,
                                                                        null,
                                                                        out mimeType,
                                                                        out encoding,
                                                                        out fileNameExtension,
                                                                        out streams,
                                                                        out warnings);

                        string año = sClaveAcceso.Substring(4, 4);

                        if (!Directory.Exists(PathServer + @"\Ride\Factura\" + año + @"\"))
                        {
                            Directory.CreateDirectory(PathServer + @"\Ride\Factura\" + año + @"\");
                        }
                        FileStream fs = new FileStream(PathServer + @"\Ride\Factura\" + año + @"\" + sClaveAcceso + ".pdf", FileMode.Create);
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Close();
                    }
                    //fin ride

                    if (!Directory.Exists(PathServer + @"\Autorizados\"))
                    {
                        Directory.CreateDirectory(PathServer + @"\Autorizados\");
                    }
                    docxmlSRI.Save(@PathServer + @"\Autorizados\" + @"\" + sClaveAcceso + ".xml");
                    //enviar correo cliente
                    if (FormarRide)
                    {
                        if (correoCliente != "" && correoCliente != "S/N")
                        {
                            enviarCorreo(@PathServer, sClaveAcceso);
                        }
                    }
                }
                else
                {
                    tipo = docxml.GetElementsByTagName("tipo")[0].InnerText;
                    //mensaje = docxml.GetElementsByTagName("mensaje")[0].InnerText;
                    infoadicional = docxml.GetElementsByTagName("informacionAdicional")[0].InnerText;
                    string fechaEmision = docxml.GetElementsByTagName("fechaEmision")[0].InnerText;
                    if (!Directory.Exists(PathServer + @"\No Autorizados\"))
                    {
                        Directory.CreateDirectory(PathServer + @"\No Autorizados\");
                    }
                    docxmlSRI.Save(@PathServer + @"\No Autorizados\" + @"\" + sClaveAcceso + ".xml");
                    string rutaNAT    = @PathServer + @"\No Autorizados\";
                    string fechafinal = Funcion.reemplazarcaracterFecha(fechaEmision);
                    //variable a guardar en la BD
                    string tipo2         = docxmlSRI.GetElementsByTagName("identificador")[0].InnerText;
                    string msg           = docxmlSRI.GetElementsByTagName("mensaje")[1].InnerText;
                    string infoAdicional = docxmlSRI.GetElementsByTagName("informacionAdicional")[0].InnerText;
                    infoAdicional = Funcion.verificarMensaje(infoAdicional);
                    objConsultas.EjecutarSQL("INSERT INTO [dbo].[TbErroresDocEnviados]([NombreXML],[Ruta],[FechaEmision] ,[EstadoError] ,[MensajeError] ,[CodigoError] ,[InformacionAdicional] )" +
                                             "VALUES ('" + sClaveAcceso + "','" + rutaNAT + "','" + fechafinal + "','" + 1 + "','" + msg + "','" + tipo2 + "','" + infoAdicional + "')");
                }
            }
            catch (Exception ex)
            {
                sResult = ex.Message;
            }
            if (estado == "")
            {
                estado = SegundoIntento(sClaveAcceso, PathServer);
            }
            return(estado);
        }