Exemple #1
0
        /// <summary>
        /// Carga del instrumento a la lista y el archivo, validando previamente los datos
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCargarAcustica_Click(object sender, EventArgs e)
        {
            if (checkBoxEqAc.Checked == true)
            {
                eq = EEq.Si;
            }
            else
            {
                eq = EEq.No;
            }

            if (!(String.IsNullOrWhiteSpace(textBoxAcustica.Text)) && cmbBoxColorAcustica.SelectedItem != null && cmbBoxClavijasAcustica.SelectedItem != null && cmbBoxEncordadoAcustica.SelectedItem != null)
            {
                SeleccionColor();
                SeleccionClavijas();
                SeleccionEncordado();

                acustica = new Acustica(eq, textBoxAcustica.Text, clavijas, color, encordado);

                //Si se dispone de stock de los materiales se agrega a la lista
                if (acustica.DisminuirStock())
                {
                    Fabrica.Guitarra = acustica;
                    Serializador.SerializarXml <List <Guitarra> >(Fabrica.listaGuitarras, $"stockInstrumentos.xml");
                    SqlInstrumentos.InsertarGuitarra(acustica); ///Inserta en base de datos
                    StockElementosDAO.ModificarStock();         //modifica stock de elementos de produccion
                    MessageBox.Show("Instrumento cargado con exito");
                }
            }
            else
            {
                ComprobarDatosIngresados();
            }
        }
        public DataTable GetTabla()
        {
            byte[]    b         = WcfServicioMgr.Instancia.Servicio.GetTabla(Sesion.Instancia.TokenSession, "F_GF_REGFALLA");
            DataTable resultado = Serializador.DeSerializar <DataTable>(b);

            return(resultado);
        }
        private static bool ImportarInforme(byte[] informe, out bool continuaImportando)
        {
            bool resultado = false;

            continuaImportando = false;
            if (informe != null)
            {
                informe = GZip.DesComprimir(informe);
                DataSet    ds        = Serializador.DeSerializar <DataSet>(informe);
                Importador imp       = new Importador();
                DataTable  dtInforme = ds.Tables["F_GF_INFORMEFALLA"];
                if (dtInforme != null)
                {
                    if (dtInforme.Rows.Count > 0)
                    {
                        long estadoInforme = (long)dtInforme.Rows[0]["D_COD_ESTADO_INF"];
                        long _pkCodPersona = (long)dtInforme.Rows[0]["PK_ORIGEN_INFORME"];
                        // si es informe revertido del mismo agente se debe descargar

                        if ((estadoInforme == (int)D_COD_ESTADO_INF.ENVIADO) ||
                            ((CNDC.BLL.Sesion.Instancia.EmpresaActual.PkCodPersona == _pkCodPersona) && (estadoInforme == (int)D_COD_ESTADO_INF.EN_ELABORACION)))
                        {
                            continuaImportando = true;
                            resultado          = imp.Importar(ds, ContenidoArchivo.Informe, true);
                        }
                    }
                }
            }
            return(resultado);
        }
Exemple #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.ExportList);

            user = Serializador.LoadFromXMLString <Usuario>(PreferenceManager.GetDefaultSharedPreferences(this).GetString("user", ""));

            lista            = FindViewById <ListView>(Resource.Id.listaExportados);
            lista.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
            {
                var progressDialog = ProgressDialog.Show(this, "Carregando", "Recebendo informações...", true);

                var t = new Thread(new ThreadStart(delegate
                {
                    var res = Request.GetInstance().Post <Pedido>("order", "get", user.Token, new HttpParam("order_code", array[e.Position].Codigo), new HttpParam("get_order_items", "1"), new HttpParam("get_order_items_product", "1"), new HttpParam("get_product_unit", "1"), new HttpParam("get_product_price", "1"));

                    RunOnUiThread(() =>
                    {
                        progressDialog.Hide();

                        if (res.status == null)
                        {
#if DEBUG
                            AlertDialog.Builder alerta = new AlertDialog.Builder(this);
                            alerta.SetTitle("Debug");
                            alerta.SetMessage(res.debug);
                            alerta.SetPositiveButton("Fechar", (s, v) => { });
                            alerta.Show();
                            return;
#else
                            Toast.MakeText(this, "Erro no servidor!", ToastLength.Long).Show();
                            return;
#endif
                        }

                        if (res.status.code == 200)
                        {
                            Intent intent = new Intent(this, typeof(OrderItemsActivity));
                            intent.PutExtra("itemList", Serializador.ToXML(res.data.Items));
                            intent.PutExtra("action", "viewOnly");
                            StartActivity(intent);
                        }
                        else if (res.status.code == 401)
                        {
                            StartActivity(new Intent(this, typeof(LogoutActivity)));
                        }
                        else
                        {
                            Toast.MakeText(this, res.status.description, ToastLength.Short).Show();
                        }
                    });
                }));
                t.Start();
            };

            Load();
        }
Exemple #5
0
        public byte[] GetTabla(string token, string nombreTabla)
        {
            AsegurarConexion(token);
            DataTable tabla = _conexion.GetTabla(nombreTabla);


            return(Serializador.Serializar(tabla));
        }
 /// <summary>
 /// Carga del formulario y lectura del archivo de instrumentos
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void FormPrincipal_Load(object sender, EventArgs e)
 {
     Fabrica.listaGuitarras = Serializador.DeserializarXml <List <Guitarra> >(FILE);
     if (Fabrica.listaGuitarras == null)
     {
         Fabrica.listaGuitarras = new List <Guitarra>();
     }
 }
        public void CuandoLaRutaEsInvalidaException()
        {
            List <Guitarra> lista;

            lista = new List <Guitarra>();

            lista = Serializador.DeserializarXml <List <Guitarra> >("unArchivo.xml");
        }
Exemple #8
0
        public byte[] TablesColumns(string token)
        {
            AsegurarConexion(token);
            PistaMgr.Instance.EscribirEnLocal("TablesColumns(): ", GetIPCliente());
            AyudanteSincronizacion       ayudanteSinc = new AyudanteSincronizacion(_conexion);
            Dictionary <string, decimal> tabla        = ayudanteSinc.TablesColumns();

            return(Serializador.Serializar(tabla));
        }
        private async void Ejecutar_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            //20186C16-C1DC-4717-8F46-407447D225BC  =   5
            //E6360E58-8BD6-4F80-B65B-8B2098760287  =   6

            var response = new DocumentoResponse();
            //try
            //{
            // Generar xml y serializar
            FacturaXml   facturaXml   = new FacturaXml();
            Serializador serializador = new Serializador();

            //var invoice = facturaXml.metodoTemp(documento);
            //response.TramaXmlSinFirma = serializador.GenerateSimpleXML(invoice);
            response.Exito = true;

            string xmlTextoPlano = Encoding.UTF8.GetString(Convert.FromBase64String(response.TramaXmlSinFirma));     // Para pruebas

            // Certificado
            rutaCertificado = "D:\\certificado\\Certificado-NuevoProveedor\\Wnl2U2wyVk01S2wyMzgzQQ%3d%3d.pfx";
            passCertificado = "53P4xfFC8sSeFRmt";

            var firmadoRequest = new FirmadoRequest
            {
                TramaXmlSinFirma    = response.TramaXmlSinFirma,
                CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes(rutaCertificado)),
                PasswordCertificado = passCertificado,
                UnSoloNodoExtension = false
            };



            EnviarDocumentoRequest enviarDocumentoRequest = new EnviarDocumentoRequest()
            {
                Ruc           = "1073580496",
                UsuarioSol    = "MODDATOS",
                ClaveSol      = "MODDATOS",
                EndPointUrl   = "https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService",
                IdDocumento   = "F001-00000001",
                TipoDocumento = "01",
                //TramaXmlFirmado = documentoFirmado.TramaXmlFirmado
            };

            var jsonEnvioDocumento = await PostSimple(enviarDocumentoRequest);


            string waiiiit = string.Empty;
            //}
            //catch (Exception ex)
            //{
            //    response.MensajeError = ex.Message;
            //    response.Pila = ex.StackTrace;
            //    response.Exito = false;
            //}
        }
Exemple #10
0
        private async void EnvDocumento_Click(object sender, EventArgs e)
        {
            try
            {
                var fileCF = Convert.ToBase64String(File.ReadAllBytes(RutaArchivo));

                var enviarDocumentoRequest = new EnviarDocumentoRequest
                {
                    Ruc             = "20556442259",
                    UsuarioSol      = "BIZLINKS",     //LC_CONTR
                    ClaveSol        = "TESTBIZLINKS", //Gq0aXgrrWG7osEa9
                    EndPointUrl     = "https://osetesting.bizlinks.com.pe/ol-ti-itcpe/billService",
                    IdDocumento     = _documento.IdDocumento,
                    TipoDocumento   = _documento.TipoDocumento,
                    TramaXmlFirmado = fileCF
                };

                ISerializador            serializador            = new Serializador();
                IServicioSunatDocumentos servicioSunatDocumentos = new ServicioSunatDocumentos();

                RespuestaComunConArchivo respuestaEnvio;
                respuestaEnvio = await new EnviarDocumento(serializador, servicioSunatDocumentos).Post(enviarDocumentoRequest);

                var rpta = (EnviarDocumentoResponse)respuestaEnvio;
                txtResult.Text = $@"{Resources.procesoCorrecto}{Environment.NewLine}{rpta.MensajeRespuesta} siendo {DateTime.Now}";
                try
                {
                    if (rpta.Exito && !string.IsNullOrEmpty(rpta.TramaZipCdr))
                    {
                        File.WriteAllBytes($"{Program.CarpetaXml}\\{_documento.IdDocumento}.xml",
                                           Convert.FromBase64String(fileCF));

                        File.WriteAllBytes($"{Program.CarpetaCdr}\\R-{respuestaEnvio.NombreArchivo}.zip",
                                           Convert.FromBase64String(rpta.TramaZipCdr));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                if (!respuestaEnvio.Exito)
                {
                    throw new ApplicationException(respuestaEnvio.MensajeError);
                }
                Hablar();
            }
            catch (Exception ex)
            {
                txtResult.Text = ex.Message;
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Exemple #11
0
        private async void BtnGetStatus_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                using (var frm = new FrmTicket())
                {
                    if (frm.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(frm.txtNroTicket.Text))
                    {
                        return;
                    }

                    var consultaTicketRequest = new ConsultaTicketRequest
                    {
                        Ruc         = txtNroRuc.Text,
                        UsuarioSol  = txtUsuarioSol.Text,
                        ClaveSol    = txtClaveSol.Text,
                        EndPointUrl = ValorSeleccionado(),
                        IdDocumento = txtSerieCorrelativo.Text,
                        NroTicket   = frm.txtNroTicket.Text
                    };

                    ISerializador            serializador            = new Serializador();
                    IServicioSunatDocumentos servicioSunatDocumentos = new ServicioSunatDocumentos();
                    EnviarDocumentoResponse  respuestaEnvio          = await new ConsultarTicket(servicioSunatDocumentos, serializador).Post(consultaTicketRequest);

                    if (!respuestaEnvio.Exito || !string.IsNullOrEmpty(respuestaEnvio.MensajeError))
                    {
                        throw new InvalidOperationException(respuestaEnvio.MensajeError);
                    }

                    File.WriteAllBytes($"{Program.CarpetaCdr}\\R-{respuestaEnvio.NombreArchivo}.zip",
                                       Convert.FromBase64String(respuestaEnvio.TramaZipCdr));

                    txtResult.Text = $@"{Resources.procesoCorrecto}{Environment.NewLine}{respuestaEnvio.MensajeRespuesta}";

                    if (chkVoz.Checked)
                    {
                        Hablar();
                    }
                }
            }
            catch (Exception ex)
            {
                txtResult.Text = ex.Message;
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Exemple #12
0
 private async Task <T> Buscar <T>(string path, DTOs.ParametrosDeBusca parametros, CancellationToken cancellationToken) where T : class
 {
     using (var requisicao = new HttpRequestMessage(HttpMethod.Post, $"buscador/{path}")
     {
         Content = new StringContent(Serializador.Serializar(parametros, this.FormatoDeSerializacao), Encoding.UTF8, this.MimeType.MediaType)
     })
     {
         return(await this.Executar(requisicao, async resposta => await resposta.Content.ReadAs <T>(cancellationToken), cancellationToken));
     }
 }
Exemple #13
0
 /// <summary>
 /// Atualização das Configurações.
 /// </summary>
 /// <param name="aplicacao">Aplicação e suas configurações para atualização.</param>
 /// <param name="cancellationToken">Instrução para eventual cancelamento da requisição.</param>
 /// <exception cref="ErroNaRequisicao">Exceção disparada se alguma falha ocorrer durante a requisição ou em seu processamento.</exception>
 public async Task Atualizar(DTOs.Aplicacao aplicacao, CancellationToken cancellationToken = default)
 {
     using (var requisicao = new HttpRequestMessage(HttpMethod.Put, $"aplicacoes/{aplicacao.Id}/configuracoes")
     {
         Content = new StringContent(Serializador.Serializar(aplicacao, this.FormatoDeSerializacao), Encoding.UTF8, this.MimeType.MediaType)
     })
     {
         await Executar(requisicao, cancellationToken);
     }
 }
Exemple #14
0
        public string GerarTicketEncriptado(AutenticacaoModel autenticacaoModel, int expiracaoEmMinuto = 180)
        {
            var autenticacaoModelSerializado = Serializador.Serializar(autenticacaoModel);
            var ticket = new FormsAuthenticationTicket(1, autenticacaoModel.Login,
                                                       DateTime.Now, DateTime.Now.AddMinutes(expiracaoEmMinuto), false, autenticacaoModelSerializado,
                                                       FormsAuthentication.FormsCookiePath);
            var ticketEncriptado = FormsAuthentication.Encrypt(ticket);

            return(ticketEncriptado);
        }
        public string setTicketEncrypted(Core.DTO.LoginViewModel AuthenticationModel, int expiracaoEmMinuto = 180)
        {
            var autenticacaoModelSerializado = Serializador.SerializarAutenticacaoModel(AuthenticationModel);
            var ticket = new FormsAuthenticationTicket(1, AuthenticationModel.Email,
                                                       DateTime.Now, DateTime.Now.AddMinutes(expiracaoEmMinuto), false, autenticacaoModelSerializado,
                                                       FormsAuthentication.FormsCookiePath);
            var ticketEncriptado = FormsAuthentication.Encrypt(ticket);

            return(ticketEncriptado);
        }
Exemple #16
0
 private void _btnIniciar_Click(object sender, EventArgs e)
 {
     _servicio = new WCF_SisFalla.ServicioSISFALLAClient();
     byte[] b = _servicio.GetRegistrosSincronizacion(FormLogin.TokenSesion, "F_GF_REGFALLA", 0, PkCodPersona);
     b = GZip.DesComprimir(b);
     _tablaRegFalla = Serializador.DeSerializar <DataTable>(b);
     _lblFallasInvolucradas.Text = _tablaRegFalla.Rows.Count + "";
     AbrirInforme();
     _timerEnvio.Enabled = true;
 }
Exemple #17
0
        static T Deserializa <T>(string valor, ETipoConteudoApi tipoConteudo)
        {
            switch (tipoConteudo)
            {
            case ETipoConteudoApi.Json:
                return(Serializador.DeserializaJson <T>(valor));
            }

            throw new NotImplementedException("Este tipo não está implementado");
        }
Exemple #18
0
        public void Serializar()

        {
            List <PresupuestoBE> Presupuestos = new List <PresupuestoBE>();

            Presupuestos = dPresup.ListarPresupuestos();
            Serializador <List <PresupuestoBE> > Serializador = new Serializador <List <PresupuestoBE> >();

            Serializador.Serializar(Presupuestos);
        }
Exemple #19
0
        public void TestSerializador()
        {
            //Arrange
            Cliente cliente = new Cliente("Pepe Peposo", "Quintana 555");

            //Act
            Serializador <Cliente> .Guardar("unArchivo.xml", cliente);

            //Assert
            Assert.IsTrue(File.Exists("unArchivo.xml"));
        }
Exemple #20
0
 /// <summary>
 /// Descarga la lista nde instrumentos desde un archivo XML
 /// </summary>
 private void DescargaDeLista()
 {
     if (FILE != null)
     {
         Fabrica.listaGuitarras = Serializador.DeserializarXml <List <Guitarra> >(FILE);
         if (Fabrica.listaGuitarras == null)
         {
             Fabrica.listaGuitarras = new List <Guitarra>();
         }
     }
 }
        public void DeserializacionXml()
        {
            //Arrange
            Turno turno;

            //act
            turno = Serializador <Turno> .DeserializarXml("turnoUniTest.xml");

            //Assert
            Assert.IsNotNull(turno);
        }
        public void DeserializacionBinario()
        {
            //Arrange
            Turno turno;

            //act
            turno = Serializador <Turno> .DeserializarBinario("turnoUniTest.bin");

            //Assert
            Assert.IsNotNull(turno);
        }
Exemple #23
0
        public byte[] GetTablaTest(string token, string nombreTabla)
        {
            DataTable tabla = null;

            PistaMgr.Instance.EscribirEnLocal("WcfServicioSISFALLA.GetTablaTest()", GetIPCliente() + " " + token + " " + nombreTabla);
            AsegurarConexion(token);
            tabla = _conexion.GetTabla(nombreTabla);
            byte[] b = Serializador.Serializar(tabla);
            b = GZip.Comprimir(b);
            return(b);
        }
Exemple #24
0
        public static bool Guardar(string tex)
        {
            Serializador <string> xml = new Serializador <string>();
            string archivo            = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + ".\\Ticket.xml";

            if (xml.Guardar(archivo, tex))
            {
                return(true);
            }
            return(false);
        }
Exemple #25
0
        /*
         * @jjla: 26/Marzo/2014
         */
        public byte[] GetInformesFallaSincronizacion(string token)
        {
            AsegurarConexion(token);
            string pista = string.Format("GetInformesFallaSincronizacion(): {0} // {1}", GetIPCliente(), _conexion.CadenaConexion);

            PistaMgr.Instance.EscribirEnLocal(pista, "SISFALLA");
            AyudanteSincronizacion ayudanteSinc = new AyudanteSincronizacion(_conexion);
            DataTable tabla = ayudanteSinc.GetSincronizacionInformesFalla();

            return(Serializador.Serializar(tabla));
        }
Exemple #26
0
        void IGuardarFC.GuardarFC()
        {
            string        ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            StringBuilder sb   = new StringBuilder();

            sb.AppendFormat(cliente.ToString());
            sb.AppendFormat("/n");
            sb.AppendFormat(negocio.GenerarFactura());

            Serializador <Negocio> .GuardarTxt(ruta, sb.ToString(), "Factura");
        }
Exemple #27
0
        private void Confirm()
        {
            string s = Serializador.ToXML <ItemPedido>(item);

            var intent = new Intent(this, typeof(OrderActivity));

            intent.AddFlags(ActivityFlags.ReorderToFront);
            intent.PutExtra("orderItem", s);
            intent.PutExtra("action", action);

            StartActivity(intent);
        }
    public static string RecuperarCV_generarPaginador(Class_Admin.cPaginador resultado, int pPage)
    {
        int pageSize = 100;// Constantes.cCantidadFilaPorPagina;

        resultado.CantidadRegistroTotal = resultado.listaCurriculumVitae.Count;
        if (resultado.listaCurriculumVitae.Count > 100) //if (resultado.listaProductos.Count > Constantes.cCantidadFilaPorPagina)//
        {
            resultado.listaCurriculumVitae = resultado.listaCurriculumVitae.Skip((pPage - 1) * pageSize).Take(pageSize).ToList();
        }
        System.Web.HttpContext.Current.Session["paginador_productosOrdenar"] = resultado;
        return(Serializador.SerializarAJson(resultado));
    }
Exemple #29
0
        private async void ToolGenerar_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                documentoElectronicoBindingSource.EndEdit();
                totalVentaTextBox.Focus();

                ISerializador     serializador = new Serializador();
                DocumentoResponse response     = new DocumentoResponse
                {
                    Exito = false
                };

                switch (_documento.TipoDocumento)
                {
                case "07":
                    response = await new GenerarNotaCredito(serializador).Post(_documento);
                    break;

                case "08":
                    response = await new GenerarNotaDedito(serializador).Post(_documento);
                    break;

                default:
                    response = await new GenerarFactura(serializador).Post(_documento);
                    break;
                }

                if (!response.Exito)
                {
                    throw new ApplicationException(response.MensajeError);
                }

                RutaArchivo = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           $"{_documento.IdDocumento}.xml");

                File.WriteAllBytes(RutaArchivo, Convert.FromBase64String(response.TramaXmlSinFirma));

                IdDocumento = _documento.IdDocumento;

                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Create your application here
			SetContentView(Resource.Layout.Home);

			FindViewById<Button>(Resource.Id.btnNovo).Click += (sender, e) => 
			{
				var user = Serializador.LoadFromXMLString<Usuario>(PreferenceManager.GetDefaultSharedPreferences(this).GetString("user", ""));
				var display = user.Lojas.Select<Loja, String>(loja => loja.ERP.Codigo + " - " + loja.ERP.Nome).ToList();
				var lojasAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItemSingleChoice, display);

				int shopIndex = 0;
					
				AlertDialog.Builder alerta = new AlertDialog.Builder(this);
				alerta.SetTitle("Informe a empresa");
				alerta.SetSingleChoiceItems(lojasAdapter, shopIndex,(s, v) => {
					shopIndex = v.Which;
				});
				alerta.SetPositiveButton("Cancelar", (s, v) => { });
				alerta.SetNegativeButton("Confirmar", (s, v) =>
				{
					PreferenceManager.GetDefaultSharedPreferences(this).Edit().PutString("shop", Serializador.ToXML(user.Lojas[shopIndex])).Apply();
					StartActivity(new Intent(this, typeof(OrderActivity)));	
				});
				alerta.Show();
			};

			FindViewById<Button>(Resource.Id.btnSalvos).Click += (sender, e) =>
			{
				StartActivity(new Intent(this, typeof(ExportListActivity)));
			};

			FindViewById<Button>(Resource.Id.btnSair).Click += (sender, e) =>
			{
				AlertDialog.Builder alert = new AlertDialog.Builder(this);
				alert.SetTitle("Sair");
				alert.SetMessage("Deseja efetuar o logout?");
				alert.SetPositiveButton("Sim", (s, v) =>
				{
					StartActivity(new Intent(this, typeof(LogoutActivity)));
				});
				alert.SetNegativeButton("Não", (s, v) => { });
				alert.Create().Show();
			};

			FindViewById<TextView>(Resource.Id.lblVendedor).Text = PreferenceManager.GetDefaultSharedPreferences(this).GetString("employeeName", "");
			FindViewById<TextView>(Resource.Id.lblVersao).Text = "versão 1.2";
			if (Request.GetInstance().Uri.Equals(Database.Teste))
				FindViewById<TextView>(Resource.Id.lblVersao).Text += " BASE TESTE";
		}
        private void btnGen_Click(object sender, EventArgs e)
        {
            try
            {
                string codigoTipoDoc;
                switch (cboTipoDoc.SelectedIndex)
                {
                    case 0:
                        codigoTipoDoc = "01";
                        break;
                    case 1:
                        codigoTipoDoc = "03";
                        break;
                    case 2:
                        codigoTipoDoc = "07";
                        break;
                    case 3:
                        codigoTipoDoc = "08";
                        break;
                    case 4:
                        codigoTipoDoc = "20";
                        break;
                    case 5:
                        codigoTipoDoc = "40";
                        break;
                    default:
                        codigoTipoDoc = "01";
                        break;
                }
                // Una vez validado el XML seleccionado procedemos con obtener el Certificado.
                var serializar = new Serializador
                {
                    RutaCertificadoDigital = Convert.ToBase64String(File.ReadAllBytes(txtRutaCertificado.Text)),
                    PasswordCertificado = txtPassCertificado.Text,
                    TipoDocumento = rbRetenciones.Checked ? 0 : 1
                };

                using (var conexion = new ConexionSunat(txtNroRuc.Text, txtUsuarioSol.Text,
                    txtClaveSol.Text, rbRetenciones.Checked ? "ServicioSunatRetenciones" : string.Empty))
                {
                    var byteArray = File.ReadAllBytes(txtSource.Text);

                    Cursor = Cursors.WaitCursor;

                    // Firmamos el XML.
                    var tramaFirmado = serializar.FirmarXml(Convert.ToBase64String(byteArray));
                    // Le damos un nuevo nombre al archivo
                    var nombreArchivo = $"{txtNroRuc.Text}-{codigoTipoDoc}-{txtSerieCorrelativo.Text}";
                    // Escribimos el archivo XML ya firmado en una nueva ubicación.
                    using (var fs = File.Create($"{nombreArchivo}.xml"))
                    {
                        var byteFirmado = Convert.FromBase64String(tramaFirmado);
                        fs.Write(byteFirmado, 0, byteFirmado.Length);
                    }
                    // Ahora lo empaquetamos en un ZIP.
                    var tramaZip = serializar.GenerarZip(tramaFirmado, nombreArchivo);

                    var resultado = conexion.EnviarDocumento(tramaZip, $"{nombreArchivo}.zip");

                    if (resultado.Item2)
                    {
                        var returnByte = Convert.FromBase64String(resultado.Item1);

                        var rutaArchivo = $"{Directory.GetCurrentDirectory()}\\R-{nombreArchivo}.zip";
                        var fs = new FileStream(rutaArchivo, FileMode.Create, FileAccess.Write);
                        fs.Write(returnByte, 0, returnByte.Length);
                        fs.Close();

                        var sb = new StringBuilder();

                        // Añadimos la respuesta del Servicio.
                        sb.AppendLine(Resources.procesoCorrecto);

                        // Extraemos el XML contenido en el archivo de respuesta como un XML.
                        var rutaArchivoXmlRespuesta = rutaArchivo.Replace(".zip", ".xml");
                        // Procedemos a desempaquetar el archivo y leer el contenido de la respuesta SUNAT.
                        using (var streamZip = ZipFile.Read(File.Open(rutaArchivo,
                            FileMode.Open,
                            FileAccess.ReadWrite)))
                        {
                            // Nos aseguramos de que el ZIP contiene al menos un elemento.
                            if (streamZip.Entries.Any())
                            {
                                if (rbRetenciones.Checked)
                                    streamZip.Entries.Last()
                                    .Extract(".", ExtractExistingFileAction.OverwriteSilently);
                                else
                                    streamZip.Entries.First()
                                        .Extract(".", ExtractExistingFileAction.OverwriteSilently);
                            }
                        }
                        // Como ya lo tenemos extraido, leemos el contenido de dicho archivo.
                        var xDoc = XDocument.Parse(File.ReadAllText(rutaArchivoXmlRespuesta));

                        var respuesta = xDoc.Descendants(XName.Get("DocumentResponse", EspacioNombres.cac))
                            .Descendants(XName.Get("Response", EspacioNombres.cac))
                            .Descendants().ToList();

                        if (respuesta.Any())
                        {
                            // La respuesta se compone de 3 valores
                            // cbc:ReferenceID
                            // cbc:ResponseCode
                            // cbc:Description
                            // Obtendremos unicamente la Descripción (la última).
                            sb.AppendLine($"Respuesta de SUNAT a las {DateTime.Now}");
                            sb.AppendLine(((XText)respuesta.Nodes().Last()).Value);
                        }

                        txtResult.Text = sb.ToString();
                        sb.Length = 0; // Limpiamos memoria del StringBuilder.
                    }
                    else
                        txtResult.Text = resultado.Item1;
                }
            }
            catch (FaultException exSer)
            {
                txtResult.Text = exSer.ToString();
            }
            catch (Exception ex)
            {
                txtResult.Text = ex.Message;
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }