internal void ShowProgressRoutine(Lfx.Types.OperationProgress progreso) { if (progreso.IsDone) { PanelProgreso.Visible = false; PanelAyuda.Visible = true; PanelPersona.Visible = false; PanelArticulo.Visible = false; } else { if (progreso.Value > 0) { ProgressBar.Maximum = progreso.Max; ProgressBar.Style = ProgressBarStyle.Continuous; if (progreso.Value <= ProgressBar.Maximum) { ProgressBar.Value = progreso.Value; } } else { ProgressBar.Style = ProgressBarStyle.Marquee; } PanelProgreso.Visible = true; PanelAyuda.Visible = false; PanelPersona.Visible = false; PanelArticulo.Visible = false; EtiquetaOperacion.Text = progreso.Name; EtiquetaDescripcion.Text = progreso.Status; PanelProgreso.Refresh(); } }
/// <summary> /// Recalcula completamente el saldo de la cuenta corriente, para corregir errores de transporte. Principalmente de uso interno /// durante verificaciones de consistencia o al desduplicar cuentas. /// </summary> public void Recalcular() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la cuenta corriente de " + this.Persona.ToString()); Progreso.Modal = false; Progreso.Begin(); System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM ctacte WHERE id_cliente=" + this.Persona.Id.ToString() + " ORDER BY " + this.CampoId); decimal Saldo = 0; Progreso.Max = Movims.Rows.Count; foreach (System.Data.DataRow Movim in Movims.Rows) { Saldo += System.Convert.ToDecimal(Movim["importe"]); qGen.Update ComandoActualizarSaldo = new qGen.Update(this.TablaDatos); ComandoActualizarSaldo.Fields.AddWithValue("saldo", Saldo); ComandoActualizarSaldo.WhereClause = new qGen.Where(this.CampoId, System.Convert.ToInt32(Movim[this.CampoId])); this.Connection.Execute(ComandoActualizarSaldo); Progreso.Advance(1); } qGen.Update ComandoActualizarCliente = new qGen.Update("personas"); ComandoActualizarCliente.Fields.AddWithValue("saldo_ctacte", Saldo); ComandoActualizarCliente.WhereClause = new qGen.Where("id_persona", this.Persona.Id); this.Connection.Execute(ComandoActualizarCliente); Progreso.End(); }
public override void OnExport(string filename, FormatoExportar formato) { System.Data.DataTable Tabla = this.Connection.Select(this.SelectCommand()); Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Generando archivos", "Leyendo información de los comprobantes"); Progreso.Max = Tabla.Rows.Count * 3; Progreso.Begin(); var ArchivoCitiVentas = new Lbl.Archivos.Salida.CitiVentas(Progreso); foreach (System.Data.DataRow Registro in Tabla.Rows) { Lbl.Comprobantes.ComprobanteFacturable ComprobanteFacturable = new Lbl.Comprobantes.ComprobanteFacturable(this.Connection, System.Convert.ToInt32(Registro["id_comprob"])); if (!ComprobanteFacturable.Anulado) { ArchivoCitiVentas.Comprobantes.Add(ComprobanteFacturable); } Progreso.Advance(1); } var ArchivoCitiAlicuotas = new Lbl.Archivos.Salida.CitiVentasAlicuotas(ArchivoCitiVentas); var NombreArchivoBase = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename)); Progreso.Description = "Generando el archivo de ventas"; ArchivoCitiVentas.Escribir(NombreArchivoBase + " Ventas.txt"); Progreso.Description = "Generando el archivo de alícuotas"; ArchivoCitiAlicuotas.Escribir(NombreArchivoBase + " Ventas Alícuotas.txt"); Progreso.End(); base.OnExport(filename, formato); }
public void MostrarProgreso(IList<Lfx.Types.OperationProgress> operaciones, Lfx.Types.OperationProgress progreso) { this.Progreso = progreso; this.TopMost = progreso.Modal; ProgressBar.Maximum = progreso.Max; if (ProgressBar.Value > 0) ProgressBar.Style = ProgressBarStyle.Continuous; else ProgressBar.Style = ProgressBarStyle.Marquee; EtiquetaNombreOperacion.Text = progreso.Name; if (operaciones.Count > 1) EtiquetaOtrasOperaciones.Text = "(Hay otras operaciones pendientes)"; EtiquetaEstado.Text = progreso.Status; EtiquetaDescripcion.Text = progreso.Description; if (progreso.Value < ProgressBar.Minimum) ProgressBar.Value = ProgressBar.Minimum; else if (progreso.Value > ProgressBar.Maximum) ProgressBar.Value = ProgressBar.Maximum; else ProgressBar.Value = progreso.Value; BotonCancelar.Visible = progreso.Cancelable; this.Refresh(); }
public Updater(string channel) { this.Channel = channel; this.Progress = new Types.OperationProgress("Actualizador", "Mantiene los archivos de la aplicación actualizados."); this.Progress.Modal = false; this.Progress.Advertise = false; this.Packages = new PackageCollection(this); }
private void BotonPresentar_Click(object sender, EventArgs e) { if (Listado.CheckedItems.Count == 0) { Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para presentar.", "Acreditar"); return; } int CantidadCupones = 0; foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { CantidadCupones++; if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar") { Lui.Forms.MessageBox.Show("Sólo se pueden hacer presentaciones de cupones que no han sido presentados.", "Presentación de cupones"); return; } } } if (CantidadCupones == 0) { Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para presentar.", "Presentación de cupones"); return; } using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea marcar los cupones seleccionados como presentados?", "Presentación de cupones")) { Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; if (Pregunta.ShowDialog() == DialogResult.OK) { IDbTransaction Trans = Connection.BeginTransaction(IsolationLevel.Serializable); Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Presentación de cupones", "Se están marcando los cupones seleccionados como 'Presentados'."); Progreso.Max = CantidadCupones; Progreso.Begin(); foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { Progreso.Advance(1); Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); if (Cupon.Estado == 0) { Cupon.Presentar(); } } } Progreso.End(); Trans.Commit(); this.RefreshList(); } } }
private void DetectarConfig() { if (this.ThreadBuscar != null) { this.ThreadBuscar.Abort(); this.ThreadBuscar = null; } switch (Lfx.Environment.SystemInformation.Platform) { case Lfx.Environment.SystemInformation.Platforms.Windows: Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Buscando un servidor", "Por favor aguarde mientras Lázaro busca un servidor en la red para utilizar como almacén de datos."); ProgresoBuscar.Visible = true; Progreso.Modal = false; Progreso.Advertise = false; Progreso.Begin(); System.Threading.ThreadStart Buscar = delegate { this.BuscarServidor(Progreso); }; this.ThreadBuscar = new System.Threading.Thread(Buscar); this.ThreadBuscar.IsBackground = true; this.ThreadBuscar.Start(); EtiquetaBuscarEspere.Visible = true; while (Progreso != null && Progreso.IsRunning) { System.Threading.Thread.Sleep(100); EtiquetaBuscando.Text = Progreso.Status; System.Windows.Forms.Application.DoEvents(); if (this.ThreadBuscar == null) { return; } } EtiquetaBuscarEspere.Visible = false; ProgresoBuscar.Visible = false; if (ServidorDetectado == null) { CheckInstalarAhora.Checked = true; EtiquetaBuscando.Text = "Lázaro no pudo encontrar un servidor SQL en la red. Si desea, puede instalar un servidor SQL en este equipo. Haga clic en 'Siguiente' para continuar."; } else { EtiquetaBuscando.Text = "Lázaro detectó un servidor SQL en la red. Haga clic en el botón 'Siguiente' para revisar la configuración detectada."; CheckOtroEquipo.Checked = true; EntradaServidor.Text = ServidorDetectado; } break; default: // No es Windows CheckInstalarAhora.Enabled = false; break; } }
private void DescargarEInstalar(Lfx.Types.OperationProgress progreso) { string InstaladorMariaDb = "InstalarMariaDB.exe"; string CarpetaDescarga; if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationFolder + @"..\WebInstall\" + InstaladorMariaDb)) { CarpetaDescarga = Lfx.Environment.Folders.ApplicationFolder + @"..\WebInstall\"; } else { progreso.ChangeStatus("Descargando, por favor aguarde..."); CarpetaDescarga = Lfx.Environment.Folders.TemporaryFolder; Lfx.Environment.Folders.EnsurePathExists(CarpetaDescarga); using (WebClient Cliente = new WebClient()) { try { Cliente.DownloadFile("http://www.lazarogestion.com/aslnlwc/" + InstaladorMariaDb, CarpetaDescarga + InstaladorMariaDb); } catch (Exception ex) { progreso.ChangeStatus("Error al descargar: " + ex.Message); } } } if (System.IO.File.Exists(CarpetaDescarga + InstaladorMariaDb)) { progreso.ChangeStatus("Instalando..."); try { Lfx.Environment.Shell.Execute(CarpetaDescarga + InstaladorMariaDb, "/verysilent /sp- /norestart", System.Diagnostics.ProcessWindowStyle.Normal, true); } catch (Exception ex) { progreso.ChangeStatus("Error al instalar: " + ex.Message); } } Lfx.Workspace.Master.ConnectionParameters.ServerName = "localhost"; Lfx.Workspace.Master.ConnectionParameters.UserName = "******"; Lfx.Workspace.Master.ConnectionParameters.Password = ""; Lfx.Data.DatabaseCache.DefaultCache.AccessMode = Lfx.Data.AccessModes.MySql; Lfx.Data.DatabaseCache.DefaultCache.SlowLink = false; Lfx.Workspace.Master.ConnectionParameters.DatabaseName = ""; Lfx.Types.OperationResult Res = this.ProbarServidor(); if (Res.Success) { if (Lfx.Workspace.Master.IsPrepared() == false) { Lfx.Workspace.Master.Prepare(progreso); } progreso.End(); } else { Lfx.Workspace.Master.RunTime.Toast("No se puede descargar o instalar el servidor SQL. Puede volver atrás para intentarlo nuevamente o salir para instalarlo de forma manual.", "Error"); } }
private void BotonAnular_Click(object sender, System.EventArgs e) { if (Listado.CheckedItems.Count == 0) { Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para anular.", "Acreditar"); return; } int CantidadCupones = 0; foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { CantidadCupones++; if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar" && itm.SubItems["estado"].Text != "Presentado") { Lui.Forms.MessageBox.Show("Sólo se pueden anular cupones que no han sido acreditados o rechazados.", "Anular de cupones"); return; } } } if (CantidadCupones == 0) { Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para anular.", "Anular de cupones"); return; } using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea eliminar de manera permanente los cupones seleccionados?", "Anular cupones")) { Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; if (Pregunta.ShowDialog() == DialogResult.OK) { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando cupones", "Se van a eleiminar los cupones seleccionados"); Progreso.Max = CantidadCupones; Progreso.Begin(); foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { Progreso.Advance(1); Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); if (Cupon.Estado == 0 || Cupon.Estado == 10) { Cupon.Anular(); } } } Progreso.End(); this.RefreshList(); } } }
public void NotifyProgress(Lfx.Types.OperationProgress progress) { if (IpcEvent != null) { IpcEventArgs e = new IpcEventArgs(); e.EventType = IpcEventArgs.EventTypes.Progress; e.Destination = "lazaro"; e.Verb = "PROGRESS"; e.Arguments = new object[] { progress }; this.IpcEvent(this, ref e); } }
public void Importar() { this.Progreso = new Lfx.Types.OperationProgress("Importando datos de " + this.Nombre, "Se están importando los datos del filtro " + this.Nombre); this.Progreso.Modal = true; this.Progreso.Begin(); this.PrepararTablasLazaro(); this.PreImportar(); this.ImportarTodo(); this.PostImportar(); this.Progreso.End(); }
/// <summary> /// Busco un servidor en la red loca. /// </summary> /// <returns></returns> private void BuscarServidor(Lfx.Types.OperationProgress progreso) { foreach (NetworkInterface Intrfc in NetworkInterface.GetAllNetworkInterfaces()) { progreso.ChangeStatus("Buscando en " + Intrfc.Name); if (Intrfc.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation MiDireccion in Intrfc.GetIPProperties().UnicastAddresses) { byte FirstByte = MiDireccion.Address.GetAddressBytes()[0]; if (FirstByte == 192 || FirstByte == 10) { byte SecondByte = MiDireccion.Address.GetAddressBytes()[1]; byte ThirdByte = MiDireccion.Address.GetAddressBytes()[2]; for (byte i = 1; i < 255; i++) { try { IPAddress DireccionServidor = new IPAddress(new byte[] { FirstByte, SecondByte, ThirdByte, i }); if (DireccionServidor.Equals(MiDireccion.Address) == false) { Ping Pp = new Ping(); PingReply Pr = Pp.Send(DireccionServidor, 100); if (Pr.Status == IPStatus.Success) { try { System.Net.Sockets.TcpClient Cliente = new System.Net.Sockets.TcpClient(); Cliente.Connect(DireccionServidor, 3306); Cliente.Close(); this.ServidorDetectado = DireccionServidor.ToString(); System.Net.IPHostEntry DireccionServidorDetectado = System.Net.Dns.GetHostEntry(ServidorDetectado); this.ServidorDetectado = DireccionServidorDetectado.HostName; progreso.End(); } catch { // Nada } } } } catch { // Ignoro esa IP } } } } } } this.ServidorDetectado = null; progreso.End(); }
public void CheckTable(Lfx.Types.OperationProgress progreso, Lfx.Data.Table table) { Lfx.Data.TableStructure CurrentTableDef = this.Connection.GetTableStructure(table.Name, true); progreso.ChangeStatus("Verificando tabla " + table.Name); foreach (Lfx.Data.ConstraintDefinition Cons in CurrentTableDef.Constraints.Values) { // Elimino valores 0 (los pongo en NULL) qGen.Update PonerNullablesEnNull = new qGen.Update(table.Name); PonerNullablesEnNull.ColumnValues.AddWithValue(Cons.Column, null); PonerNullablesEnNull.WhereClause = new qGen.Where(Cons.Column, 0); this.Connection.ExecuteNonQuery(PonerNullablesEnNull); // Busco problemas de integridad referencial if (Cons.TableName != Cons.ReferenceTable) { qGen.Select RefValidas = new qGen.Select(Cons.ReferenceTable); RefValidas.Columns = new qGen.SqlIdentifierCollection() { Cons.ReferenceColumn }; qGen.Update ElimRefInvalidas = new qGen.Update(table.Name); switch (Cons.ReferenceTable) { case "bancos": // Los bancos inexistentes los remplazo por "otro banco" ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, 99); break; case "personas": // Las personas inexistentes las paso a Administrador ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, 1); break; default: // El resto lo pongo en null ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, null); break; } ElimRefInvalidas.WhereClause = new qGen.Where(Cons.Column, qGen.ComparisonOperators.NotIn, RefValidas); System.Console.WriteLine(ElimRefInvalidas.ToString()); this.Connection.ExecuteNonQuery(ElimRefInvalidas); } } }
public void CheckDataBase() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Verificando integridad de los datos", "Se está verificando la consistencia de los datos almacenados."); Progreso.Advertise = true; Progreso.Modal = true; Progreso.Begin(); this.DataBase.ExecuteSql("ALTER DATABASE " + this.DataBase.DataBaseName + " charset=utf8"); Progreso.ChangeStatus("Recalculando existencias de artículos"); // Actualizo los saldos de stock, se acuerdo a stock_movim this.DataBase.ExecuteSql(@"UPDATE articulos SET stock_actual=(SELECT saldo FROM articulos_movim WHERE articulos_movim.id_articulo=articulos.id_articulo ORDER BY id_movim DESC LIMIT 1) WHERE control_stock<>0" ); this.DataBase.ExecuteSql(@"UPDATE articulos SET stock_actual=0 WHERE control_stock=0"); /* * // Verificar saldos de cuentas corrientes * string Sql = @"SELECT personas.id_persona * FROM personas LEFT JOIN ctacte ON personas.id_persona=ctacte.id_cliente * GROUP BY personas.id_persona * HAVING SUM(ctacte.importe)<>(SELECT saldo FROM ctacte WHERE ctacte.id_cliente=personas.id_persona ORDER BY id_movim DESC LIMIT 1)"; * System.Data.DataTable CuentasMal = this.DataBase.Select(Sql); * foreach (System.Data.DataRow Cuenta in CuentasMal.Rows) { * int IdCliente = System.Convert.ToInt32(Cuenta["id_persona"]); * Lbl.Personas.Persona Cliente = new Lbl.Personas.Persona(this.DataBase, IdCliente); * Cliente.CuentaCorriente.Recalcular(); * } */ foreach (Lfx.Data.Table Tbl in Lfx.Data.DataBaseCache.DefaultCache.Tables) { CheckTable(Progreso, Tbl); } Progreso.End(); // TODO: verificar saldos de cajas }
private void BotonInstalar_Click(object sender, EventArgs e) { BotonInstalar.Enabled = false; BotonSiguiente.Enabled = false; EtiquetaDescargando.Text = "Descargando, por favor aguarde..."; EtiquetaDescargando.Visible = true; ProgresoDescargando.Visible = true; if (this.ThreadDescargar != null) { this.ThreadDescargar.Abort(); this.ThreadDescargar = null; } Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Instalar servidor SQL", "Se está descargando, instalando y configurando un servidor SQL en este equipo"); Progreso.Advertise = false; Progreso.Modal = false; Progreso.Begin(); System.Threading.ThreadStart Buscar = delegate { this.DescargarEInstalar(Progreso); }; this.ThreadDescargar = new System.Threading.Thread(Buscar); this.ThreadDescargar.IsBackground = true; this.ThreadDescargar.Start(); while (Progreso != null && Progreso.IsRunning) { System.Threading.Thread.Sleep(100); EtiquetaDescargando.Text = Progreso.Status; System.Windows.Forms.Application.DoEvents(); if (this.ThreadDescargar == null) { // Cancelar return; } } EtiquetaDescargando.Text = "Continuando..."; Paso = Inicial.Pasos.DatosEmpresa; this.MostrarPaneles(); }
public void MostrarProgreso(IList <Lfx.Types.OperationProgress> operaciones, Lfx.Types.OperationProgress progreso) { this.Progreso = progreso; this.TopMost = progreso.Modal; ProgressBar.Maximum = progreso.Max; if (ProgressBar.Value > 0) { ProgressBar.Style = ProgressBarStyle.Continuous; } else { ProgressBar.Style = ProgressBarStyle.Marquee; } EtiquetaNombreOperacion.Text = progreso.Name; if (operaciones.Count > 1) { EtiquetaOtrasOperaciones.Text = "(Hay otras operaciones pendientes)"; } EtiquetaEstado.Text = progreso.Status; EtiquetaDescripcion.Text = progreso.Description; if (progreso.Value < ProgressBar.Minimum) { ProgressBar.Value = ProgressBar.Minimum; } else if (progreso.Value > ProgressBar.Maximum) { ProgressBar.Value = ProgressBar.Maximum; } else { ProgressBar.Value = progreso.Value; } BotonCancelar.Visible = progreso.Cancelable; this.Refresh(); }
public void CheckDataBase() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Verificando integridad de los datos", "Se está verificando la consistencia de los datos almacenados."); Progreso.Advertise = true; Progreso.Modal = true; Progreso.Begin(); this.DataBase.ExecuteSql("ALTER DATABASE " + this.DataBase.DataBaseName + " charset=utf8"); Progreso.ChangeStatus("Recalculando existencias de artículos"); // Actualizo los saldos de stock, se acuerdo a stock_movim this.DataBase.ExecuteSql(@"UPDATE articulos SET stock_actual=(SELECT saldo FROM articulos_movim WHERE articulos_movim.id_articulo=articulos.id_articulo ORDER BY id_movim DESC LIMIT 1) WHERE control_stock<>0"); this.DataBase.ExecuteSql(@"UPDATE articulos SET stock_actual=0 WHERE control_stock=0"); /* // Verificar saldos de cuentas corrientes string Sql = @"SELECT personas.id_persona FROM personas LEFT JOIN ctacte ON personas.id_persona=ctacte.id_cliente GROUP BY personas.id_persona HAVING SUM(ctacte.importe)<>(SELECT saldo FROM ctacte WHERE ctacte.id_cliente=personas.id_persona ORDER BY id_movim DESC LIMIT 1)"; System.Data.DataTable CuentasMal = this.DataBase.Select(Sql); foreach (System.Data.DataRow Cuenta in CuentasMal.Rows) { int IdCliente = System.Convert.ToInt32(Cuenta["id_persona"]); Lbl.Personas.Persona Cliente = new Lbl.Personas.Persona(this.DataBase, IdCliente); Cliente.CuentaCorriente.Recalcular(); } */ foreach (Lfx.Data.Table Tbl in Lfx.Data.DataBaseCache.DefaultCache.Tables) { CheckTable(Progreso, Tbl); } Progreso.End(); // TODO: verificar saldos de cajas }
/// <summary> /// Recalcula completamente el saldo de la caja, para corregir errores de transporte. Principalmente de uso interno. /// </summary> public void Recalcular() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la caja " + this.ToString()); Progreso.Begin(); System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM cajas_movim WHERE id_caja=" + this.Caja.Id.ToString() + " ORDER BY id_movim"); decimal Saldo = 0; Progreso.Max = Movims.Rows.Count; foreach (System.Data.DataRow Movim in Movims.Rows) { Saldo += System.Convert.ToDecimal(Movim["importe"]); qGen.Update Upd = new qGen.Update("cajas_movim"); Upd.ColumnValues.AddWithValue("saldo", Saldo); Upd.WhereClause = new qGen.Where("id_movim", System.Convert.ToInt32(Movim["id_movim"])); this.Connection.ExecuteNonQuery(Upd); Progreso.Advance(1); } Progreso.End(); }
private bool AnularSinNumero() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando comprobantes", "Se están anulando los comprobantes seleccionados."); Progreso.Cancelable = true; Progreso.Max = 1; Progreso.Begin(); IDbTransaction Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable); Lbl.Comprobantes.ComprobanteConArticulos Fac = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdAnular); if (Fac.Anulado == false) { Fac.Anular(false); } Progreso.Advance(1); Progreso.End(); if (Progreso.Cancelar) { Trans.Rollback(); Lfx.Workspace.Master.RunTime.Toast("La operación fue cancelada.", "Aviso"); return(false); } else { Trans.Commit(); ProximosNumeros.Clear(); if (this.DeCompra) { Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Si fueron anulados por error de carga, ahora puede cargarlos nuevamente.", "Aviso"); } else { Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Recuerde archivar ambas copias.", "Aviso"); } return(true); } }
private void Imprimir() { Lfx.Types.OperationResult Res; if (this.ReadOnly) { Res = new Lfx.Types.SuccessOperationResult(); } else { if (this.Elemento.Existe == false) { // Si es nuevo, lo guardo sin preguntar. Res = this.Save(); } else if (this.Changed) { // Si es edición, y hay cambios, pregunto si quiere guardar using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hay modificaciones sin guardar (subrayadas en color rojo). Antes de imprimir el ducumento se guardarán las modificaciones. ¿Desea continuar?", "Imprimir")) { Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; this.ShowChanged = true; if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Res = this.Save(); } else { Res = new Lfx.Types.CancelOperationResult(); } this.ShowChanged = false; } } else { // Es edición y no hay cambios... continúo Res = new Lfx.Types.SuccessOperationResult(); } } if (Res.Success) Res = this.ControlUnico.BeforePrint(); if (Res.Success) { Lbl.Impresion.Impresora Impresora = null; if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift) { using (Lui.Printing.PrinterSelectionDialog FormularioSeleccionarImpresora = new Lui.Printing.PrinterSelectionDialog()) { if (FormularioSeleccionarImpresora.ShowDialog() == DialogResult.OK) { Impresora = FormularioSeleccionarImpresora.SelectedPrinter; } else { return; } } } string NombreDocumento = Elemento.ToString(); Lbl.Impresion.CargasPapel Carga = Lbl.Impresion.CargasPapel.Automatica; if (Impresora != null && Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Manual) { Carga = Lbl.Impresion.CargasPapel.Manual; } else if (this.Elemento is Lbl.Comprobantes.ComprobanteConArticulos) { Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos; if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV].Tipo == Lbl.Comprobantes.TipoPv.Fiscal) { Carga = Lbl.Impresion.CargasPapel.Automatica; } else { // El tipo de comprobante puede forzar a una carga manual Carga = Comprob.Tipo.CargaPapel; // Intento averiguar el número de comprobante, en caso de que aun no esté numerado if (Comprob.Numero == 0) { int ProximoNumero = Lbl.Comprobantes.Numerador.ProximoNumero(Comprob); NombreDocumento = NombreDocumento.Replace("00000000", ProximoNumero.ToString("00000000")); } } } if (Carga == Lbl.Impresion.CargasPapel.Manual) { using (Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog()) { FormularioCargaManual.DocumentName = NombreDocumento; // Muestro el nombre de la impresora if (Impresora != null) { FormularioCargaManual.PrinterName = Impresora.Nombre; } else { System.Drawing.Printing.PrinterSettings ObjPrint = new System.Drawing.Printing.PrinterSettings(); FormularioCargaManual.PrinterName = ObjPrint.PrinterName; } if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel) return; } } if (Impresora != null && Impresora.EsVistaPrevia) { Lazaro.Impresion.ImpresorElemento ImpresorVistaPrevia = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, null); ImpresorVistaPrevia.PrintController = new System.Drawing.Printing.PreviewPrintController(); Lui.Printing.PrintPreviewForm VistaPrevia = new Lui.Printing.PrintPreviewForm(); VistaPrevia.MdiParent = this.ParentForm.MdiParent; VistaPrevia.PrintPreview.Document = ImpresorVistaPrevia; VistaPrevia.Show(); } else { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Imprimiendo", "El documento se está enviando a la impresora."); if (Impresora != null) Progreso.Description = "El documento se está enviando a la impresora " + Impresora.ToString(); Progreso.Modal = false; Progreso.Begin(); using (IDbTransaction Trans = this.Elemento.Connection.BeginTransaction()) { Lazaro.Impresion.ImpresorElemento Impresor = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, Trans); Impresor.Impresora = Impresora; try { Res = Impresor.Imprimir(); } catch (Exception ex) { Res = new Lfx.Types.FailureOperationResult(ex.Message); } Progreso.End(); if (Res.Success == false) { if (Impresor.Transaction != null) // Puede que la transacción ya haya sido finalizada por el impresor Impresor.Transaction.Rollback(); Lui.Forms.MessageBox.Show(Res.Message, "Error"); } else { if (Impresor.Transaction != null) // Puede que la transacción ya haya sido finalizada por el impresor Impresor.Transaction.Commit(); this.Elemento.Cargar(); this.FromRow(this.Elemento); this.ControlUnico.AfterPrint(); } } } } if (Res.Success == false && Res.Message != null) { Lui.Forms.MessageBox.Show(Res.Message, "Imprimir"); } }
private void BotonInstalar_Click(object sender, EventArgs e) { BotonInstalar.Enabled = false; BotonSiguiente.Enabled = false; EtiquetaDescargando.Text = "Descargando, por favor aguarde..."; EtiquetaDescargando.Visible = true; ProgresoDescargando.Visible = true; if (this.ThreadDescargar != null) { this.ThreadDescargar.Abort(); this.ThreadDescargar = null; } Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Instalar servidor SQL", "Se está descargando, instalando y configurando un servidor SQL en este equipo"); Progreso.Advertise = false; Progreso.Modal = false; Progreso.Begin(); System.Threading.ThreadStart Buscar = delegate { this.DescargarEInstalar(Progreso); }; this.ThreadDescargar = new System.Threading.Thread(Buscar); this.ThreadDescargar.IsBackground = true; this.ThreadDescargar.Start(); while (Progreso != null && Progreso.IsRunning) { System.Threading.Thread.Sleep(100); EtiquetaDescargando.Text = Progreso.Status; System.Windows.Forms.Application.DoEvents(); if (this.ThreadDescargar == null) // Cancelar return; } EtiquetaDescargando.Text = "Continuando..."; Paso = Inicial.Pasos.DatosEmpresa; this.MostrarPaneles(); }
private void Imprimir() { Lfx.Types.OperationResult Res; if (this.ReadOnly) { Res = new Lfx.Types.SuccessOperationResult(); } else { if (this.Elemento.Existe == false) { // Si es nuevo, lo guardo sin preguntar. Res = this.Save(); } else if (this.Changed) { // Si es edición, y hay cambios, pregunto si quiere guardar using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hay modificaciones sin guardar (subrayadas en color rojo). Antes de imprimir el ducumento se guardarán las modificaciones. ¿Desea continuar?", "Imprimir")) { Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; this.ShowChanged = true; if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Res = this.Save(); } else { Res = new Lfx.Types.CancelOperationResult(); } this.ShowChanged = false; } } else { // Es edición y no hay cambios... continúo Res = new Lfx.Types.SuccessOperationResult(); } } if (Res.Success) { Res = this.ControlUnico.BeforePrint(); } if (Res.Success) { Lbl.Impresion.Impresora Impresora = null; if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift) { using (Lui.Printing.PrinterSelectionDialog FormularioSeleccionarImpresora = new Lui.Printing.PrinterSelectionDialog()) { if (FormularioSeleccionarImpresora.ShowDialog() == DialogResult.OK) { Impresora = FormularioSeleccionarImpresora.SelectedPrinter; } else { return; } } } string NombreDocumento = Elemento.ToString(); Lbl.Impresion.CargasPapel Carga = Lbl.Impresion.CargasPapel.Automatica; if (Impresora != null && Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Manual) { Carga = Lbl.Impresion.CargasPapel.Manual; } else if (this.Elemento is Lbl.Comprobantes.ComprobanteConArticulos) { Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos; if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV].Tipo == Lbl.Comprobantes.TipoPv.Fiscal) { Carga = Lbl.Impresion.CargasPapel.Automatica; } else { // El tipo de comprobante puede forzar a una carga manual Carga = Comprob.Tipo.CargaPapel; // Intento averiguar el número de comprobante, en caso de que aun no esté numerado if (Comprob.Numero == 0) { int ProximoNumero = Lbl.Comprobantes.Numerador.ProximoNumero(Comprob); NombreDocumento = NombreDocumento.Replace("00000000", ProximoNumero.ToString("00000000")); } } } if (Carga == Lbl.Impresion.CargasPapel.Manual) { using (Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog()) { FormularioCargaManual.DocumentName = NombreDocumento; // Muestro el nombre de la impresora if (Impresora != null) { FormularioCargaManual.PrinterName = Impresora.Nombre; } else { System.Drawing.Printing.PrinterSettings ObjPrint = new System.Drawing.Printing.PrinterSettings(); FormularioCargaManual.PrinterName = ObjPrint.PrinterName; } if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel) { return; } } } if (Impresora != null && Impresora.EsVistaPrevia) { Lazaro.Impresion.ImpresorElemento ImpresorVistaPrevia = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, null); ImpresorVistaPrevia.PrintController = new System.Drawing.Printing.PreviewPrintController(); Lui.Printing.PrintPreviewForm VistaPrevia = new Lui.Printing.PrintPreviewForm(); VistaPrevia.MdiParent = this.ParentForm.MdiParent; VistaPrevia.PrintPreview.Document = ImpresorVistaPrevia; VistaPrevia.Show(); } else { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Imprimiendo", "El documento se está enviando a la impresora."); if (Impresora != null) { Progreso.Description = "El documento se está enviando a la impresora " + Impresora.ToString(); } Progreso.Modal = false; Progreso.Begin(); using (IDbTransaction Trans = this.Elemento.Connection.BeginTransaction()) { Lazaro.Impresion.ImpresorElemento Impresor = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, Trans); Impresor.Impresora = Impresora; try { Res = Impresor.Imprimir(); } catch (Exception ex) { Res = new Lfx.Types.FailureOperationResult(ex.Message); } Progreso.End(); if (Res.Success == false) { if (Impresor.Transaction != null) { // Puede que la transacción ya haya sido finalizada por el impresor Impresor.Transaction.Rollback(); } Lui.Forms.MessageBox.Show(Res.Message, "Error"); } else { if (Impresor.Transaction != null) { // Puede que la transacción ya haya sido finalizada por el impresor Impresor.Transaction.Commit(); } this.Elemento.Cargar(); this.FromRow(this.Elemento); this.ControlUnico.AfterPrint(); } } } } if (Res.Success == false && Res.Message != null) { Lui.Forms.MessageBox.Show(Res.Message, "Imprimir"); } }
private void ProcesarReimpresion(string tipo, int pv, int desde, int hasta) { using (Lfx.Data.Connection Conn = Lfx.Workspace.Master.GetNewConnection("Reimpresión de comprobantes")) { int Cantidad = Math.Abs(hasta - desde); Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Reimprimiendo", "Se están reimprimiendo " + Cantidad.ToString() + " comprobantes."); Progreso.Cancelable = true; Progreso.Max = Cantidad; Progreso.Modal = true; Progreso.Advertise = true; Progreso.Begin(); string IncluyeTipos = ""; switch (tipo) { case "A": IncluyeTipos = "'FA', 'NCA', 'NDA'"; break; case "B": IncluyeTipos = "'FB', 'NCB', 'NDB'"; break; case "C": IncluyeTipos = "'FC', 'NCC', 'NDC'"; break; case "E": IncluyeTipos = "'FE', 'NCE', 'NDE'"; break; case "M": IncluyeTipos = "'FM', 'NCM', 'NDM'"; break; default: IncluyeTipos = "'" + EntradaTipo.TextKey + "'"; break; } int Paso = desde < hasta ? 1 : -1; for (int Numero = desde; Numero != hasta; Numero += Paso) { int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND anulada=0 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + pv.ToString() + " AND numero=" + Numero.ToString()); if (IdFactura == 0) { // No existe, supongo que está anulado, lo salteo } else { Lbl.Comprobantes.ComprobanteFacturable Fac = new Lbl.Comprobantes.ComprobanteFacturable(Conn, IdFactura); Progreso.ChangeStatus("Imprimiendo " + Fac.ToString()); Lazaro.Impresion.Comprobantes.ImpresorComprobanteConArticulos Impr = new Lazaro.Impresion.Comprobantes.ImpresorComprobanteConArticulos(Fac, null); Impr.Imprimir(); } Progreso.Advance(1); if (Progreso.Cancelar) { break; } } Progreso.End(); } }
private void BotonAcreditar_Click(object sender, System.EventArgs e) { if (Listado.CheckedItems.Count == 0) { Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para acreditar.", "Acreditar"); return; } using (Lfc.Tarjetas.Cupones.Acreditar FormularioAcreditacion = new Lfc.Tarjetas.Cupones.Acreditar()) { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Acreditando cupones", "Se están marcando los cupones seleccionados como 'Acreditado'."); Progreso.Modal = false; decimal Total = 0; decimal TotalAcreditar = 0; int iCantidad = 0; System.Text.StringBuilder Cupones = new System.Text.StringBuilder(); decimal ComisionTarjeta = 0; decimal ComisionPlan = 0; decimal GestionDeCobro = 0; Progreso.Max = Listado.Items.Count + 2; Progreso.Begin(); Progreso.ChangeStatus("Analizando"); Lbl.Pagos.FormaDePago Tarjeta = null; foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { iCantidad++; Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); Total += Cupon.Importe; if (Cupones.Length > 0) Cupones.Append("," + Cupon.Numero); else Cupones.Append(Cupon.Numero); if (Cupon.FormaDePago != null) { if (Tarjeta == null) { Tarjeta = Cupon.FormaDePago; } else if (Tarjeta.Id != Cupon.FormaDePago.Id) { //Mezcla de tarjetas Progreso.End(); Lui.Forms.MessageBox.Show("No todos los cupones seleccionados pertenecen a la misma forma de pago.", "Error"); return; } ComisionTarjeta += Cupon.Importe * (Tarjeta.Retencion / 100); if (Cupon.Plan != null) { ComisionPlan += Cupon.Importe * (Cupon.Plan.Comision / 100); } } } Progreso.ChangeStatus(itm.Index); } FormularioAcreditacion.IgnorarCambios = true; FormularioAcreditacion.EntradaCuponesCantidad.Text = iCantidad.ToString(); FormularioAcreditacion.EntradaCuponesSubTotal.Text = Lfx.Types.Formatting.FormatCurrency(Total, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionTarjeta.Text = Lfx.Types.Formatting.FormatCurrency(ComisionTarjeta, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionPlan.Text = Lfx.Types.Formatting.FormatCurrency(ComisionPlan, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionUsuario.Text = "0"; FormularioAcreditacion.EntradaTotal.Text = Lfx.Types.Formatting.FormatCurrency(Total - ComisionTarjeta - ComisionPlan, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.IgnorarCambios = false; bool Aceptar = false; Lfc.Comprobantes.Recibos.EditarCobro FormularioPago = new Lfc.Comprobantes.Recibos.EditarCobro(); do { if (FormularioAcreditacion.ShowDialog() == DialogResult.OK) { TotalAcreditar = Lfx.Types.Parsing.ParseCurrency(FormularioAcreditacion.EntradaTotal.Text); GestionDeCobro = Total - TotalAcreditar; FormularioPago.Cobro.FromCobro(new Lbl.Comprobantes.Cobro(this.Connection, ((Lbl.Pagos.TiposFormasDePago)(Lfx.Types.Parsing.ParseInt(FormularioAcreditacion.EntradaFormaPago.TextKey))))); FormularioPago.Cobro.FormaDePagoEditable = false; FormularioPago.Cobro.Importe = TotalAcreditar; FormularioPago.Cobro.ImporteEditable = false; if (Tarjeta != null && Tarjeta.Caja != null) FormularioPago.Cobro.EntradaCaja.ValueInt = Tarjeta.Caja.Id; FormularioPago.Cobro.Obs = "Cupones Nº " + Cupones.ToString(); FormularioPago.Cobro.ObsEditable = false; if (FormularioPago.ShowDialog() == DialogResult.OK) { Aceptar = true; break; } } else { Aceptar = false; break; } } while (true); if (Aceptar) { IDbTransaction Trans = Connection.BeginTransaction(IsolationLevel.Serializable); Progreso.ChangeStatus("Asentando el movimiento"); Progreso.Max = Listado.Items.Count + 2; Progreso.Begin(); // Marcar los cupones como acreditados foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); if (Cupon.Estado == 0 || Cupon.Estado == 10) Cupon.Acreditar(); } Progreso.ChangeStatus(itm.Index); } Progreso.ChangeStatus("Acreditando el importe"); // Acreditar el dinero Lbl.Comprobantes.Cobro MiCobro = FormularioPago.Cobro.ToCobro(Connection); switch (FormularioPago.Cobro.FormaDePago.Tipo) { case Lbl.Pagos.TiposFormasDePago.Efectivo: Lbl.Cajas.Caja CajaDiaria = new Lbl.Cajas.Caja(Connection, Lfx.Workspace.Master.CurrentConfig.Empresa.CajaDiaria); CajaDiaria.Movimiento(true, Lbl.Cajas.Concepto.IngresosPorFacturacion, "Acreditación de Cupones", null, Total, "Cupones Nº " + Cupones.ToString(), null, null, null); CajaDiaria.Movimiento(true, new Lbl.Cajas.Concepto(this.Connection, 24010), "Gestión de Cobro de Cupones", null, -GestionDeCobro, "Cupones Nº " + Cupones.ToString(), null, null, null); break; case Lbl.Pagos.TiposFormasDePago.ChequePropio: Lbl.Bancos.Cheque Cheque = MiCobro.Cheque; Cheque.Concepto = Lbl.Cajas.Concepto.IngresosPorFacturacion; Cheque.ConceptoTexto = "Acreditación Tarjetas"; Cheque.Guardar(); break; case Lbl.Pagos.TiposFormasDePago.Caja: MiCobro.CajaDestino.Movimiento(true, Lbl.Cajas.Concepto.IngresosPorFacturacion, "Acreditación de Cupones", null, Total, "Cupones Nº " + Cupones.ToString(), null, null, null); MiCobro.CajaDestino.Movimiento(true, new Lbl.Cajas.Concepto(this.Connection, 24010), "Gestión de Cobro de Cupones", null, -GestionDeCobro, "Cupones Nº " + Cupones.ToString(), null, null, null); break; } Trans.Commit(); Progreso.End(); } } this.RefreshList(); }
private void BotonAcreditar_Click(object sender, System.EventArgs e) { if (Listado.CheckedItems.Count == 0) { Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para acreditar.", "Acreditar"); return; } using (Lfc.Tarjetas.Cupones.Acreditar FormularioAcreditacion = new Lfc.Tarjetas.Cupones.Acreditar()) { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Acreditando cupones", "Se están marcando los cupones seleccionados como 'Acreditado'."); Progreso.Modal = false; decimal Total = 0; decimal TotalAcreditar = 0; int iCantidad = 0; System.Text.StringBuilder Cupones = new System.Text.StringBuilder(); decimal ComisionTarjeta = 0; decimal ComisionPlan = 0; decimal GestionDeCobro = 0; Progreso.Max = Listado.Items.Count + 2; Progreso.Begin(); Progreso.ChangeStatus("Analizando"); Lbl.Pagos.FormaDePago Tarjeta = null; foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { iCantidad++; Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); Total += Cupon.Importe; if (Cupones.Length > 0) { Cupones.Append("," + Cupon.Numero); } else { Cupones.Append(Cupon.Numero); } if (Cupon.FormaDePago != null) { if (Tarjeta == null) { Tarjeta = Cupon.FormaDePago; } else if (Tarjeta.Id != Cupon.FormaDePago.Id) { //Mezcla de tarjetas Progreso.End(); Lui.Forms.MessageBox.Show("No todos los cupones seleccionados pertenecen a la misma forma de pago.", "Error"); return; } ComisionTarjeta += Cupon.Importe * (Tarjeta.Retencion / 100); if (Cupon.Plan != null) { ComisionPlan += Cupon.Importe * (Cupon.Plan.Comision / 100); } } } Progreso.ChangeStatus(itm.Index); } FormularioAcreditacion.IgnorarCambios = true; FormularioAcreditacion.EntradaCuponesCantidad.Text = iCantidad.ToString(); FormularioAcreditacion.EntradaCuponesSubTotal.Text = Lfx.Types.Formatting.FormatCurrency(Total, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionTarjeta.Text = Lfx.Types.Formatting.FormatCurrency(ComisionTarjeta, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionPlan.Text = Lfx.Types.Formatting.FormatCurrency(ComisionPlan, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.EntradaComisionUsuario.Text = "0"; FormularioAcreditacion.EntradaTotal.Text = Lfx.Types.Formatting.FormatCurrency(Total - ComisionTarjeta - ComisionPlan, Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales); FormularioAcreditacion.IgnorarCambios = false; bool Aceptar = false; Lfc.Comprobantes.Recibos.EditarCobro FormularioPago = new Lfc.Comprobantes.Recibos.EditarCobro(); do { if (FormularioAcreditacion.ShowDialog() == DialogResult.OK) { TotalAcreditar = Lfx.Types.Parsing.ParseCurrency(FormularioAcreditacion.EntradaTotal.Text); GestionDeCobro = Total - TotalAcreditar; FormularioPago.Cobro.FromCobro(new Lbl.Comprobantes.Cobro(this.Connection, ((Lbl.Pagos.TiposFormasDePago)(Lfx.Types.Parsing.ParseInt(FormularioAcreditacion.EntradaFormaPago.TextKey))))); FormularioPago.Cobro.FormaDePagoEditable = false; FormularioPago.Cobro.Importe = TotalAcreditar; FormularioPago.Cobro.ImporteEditable = false; if (Tarjeta != null && Tarjeta.Caja != null) { FormularioPago.Cobro.EntradaCaja.ValueInt = Tarjeta.Caja.Id; } FormularioPago.Cobro.Obs = "Cupones Nº " + Cupones.ToString(); FormularioPago.Cobro.ObsEditable = false; if (FormularioPago.ShowDialog() == DialogResult.OK) { Aceptar = true; break; } } else { Aceptar = false; break; } }while (true); if (Aceptar) { IDbTransaction Trans = Connection.BeginTransaction(IsolationLevel.Serializable); Progreso.ChangeStatus("Asentando el movimiento"); Progreso.Max = Listado.Items.Count + 2; Progreso.Begin(); // Marcar los cupones como acreditados foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); if (Cupon.Estado == 0 || Cupon.Estado == 10) { Cupon.Acreditar(); } } Progreso.ChangeStatus(itm.Index); } Progreso.ChangeStatus("Acreditando el importe"); // Acreditar el dinero Lbl.Comprobantes.Cobro MiCobro = FormularioPago.Cobro.ToCobro(Connection); switch (FormularioPago.Cobro.FormaDePago.Tipo) { case Lbl.Pagos.TiposFormasDePago.Efectivo: Lbl.Cajas.Caja CajaDiaria = new Lbl.Cajas.Caja(Connection, Lfx.Workspace.Master.CurrentConfig.Empresa.CajaDiaria); CajaDiaria.Movimiento(true, Lbl.Cajas.Concepto.IngresosPorFacturacion, "Acreditación de Cupones", null, Total, "Cupones Nº " + Cupones.ToString(), null, null, null); CajaDiaria.Movimiento(true, new Lbl.Cajas.Concepto(this.Connection, 24010), "Gestión de Cobro de Cupones", null, -GestionDeCobro, "Cupones Nº " + Cupones.ToString(), null, null, null); break; case Lbl.Pagos.TiposFormasDePago.ChequePropio: Lbl.Bancos.Cheque Cheque = MiCobro.Cheque; Cheque.Concepto = Lbl.Cajas.Concepto.IngresosPorFacturacion; Cheque.ConceptoTexto = "Acreditación Tarjetas"; Cheque.Guardar(); break; case Lbl.Pagos.TiposFormasDePago.Caja: MiCobro.CajaDestino.Movimiento(true, Lbl.Cajas.Concepto.IngresosPorFacturacion, "Acreditación de Cupones", null, Total, "Cupones Nº " + Cupones.ToString(), null, null, null); MiCobro.CajaDestino.Movimiento(true, new Lbl.Cajas.Concepto(this.Connection, 24010), "Gestión de Cobro de Cupones", null, -GestionDeCobro, "Cupones Nº " + Cupones.ToString(), null, null, null); break; } Trans.Commit(); Progreso.End(); } } this.RefreshList(); }
/// <summary> /// Verifica la estructura de la base de datos actual y si es necesario modifica para que esté conforme /// al diseño de referencia. /// </summary> /// <param name="connection">PrintDatabase mediante el cual se accede a la base de datos.</param> /// <param name="omitPreAndPostSql">Omitir la ejecución de comandos Pre- y Post-actualización de estructura. Esto es útil cuando se actualiza una estructura vacía, por ejemplo al crear una base de datos nueva.</param> /// /// <param name="progreso">El objeto sobre el cual reportar el progreso.</param> public void CheckAndUpdateDatabaseStructure(Lfx.Data.IConnection connection, bool omitPreAndPostSql, Lfx.Types.OperationProgress progreso) { progreso.ChangeStatus("Verificando estructuras de datos"); bool MustEnableConstraints = false; if (connection.ConstraintsEnabled) { connection.EnableConstraints(false); MustEnableConstraints = true; } if (omitPreAndPostSql == false) { progreso.ChangeStatus("Ejecutando guión previo..."); InyectarSqlDesdeRecurso(connection, @"Data.Struct.db_upd_pre.sql"); } //Primero borro claves foráneas (deleteOnly = true) progreso.ChangeStatus("Eliminando reglas obsoletas..."); connection.SetConstraints(Lfx.Workspace.Master.Structure.Constraints, true); try { connection.ExecuteNonQuery("FLUSH TABLES"); } catch { // No tengo permiso... no importa } progreso.Max = Lfx.Workspace.Master.Structure.Tables.Count; foreach (Lfx.Data.TableStructure Tab in Lfx.Workspace.Master.Structure.Tables.Values) { string TableLabel = Tab.Label; if (Tab.Label == null) { TableLabel = Tab.Name.ToTitleCase(); } progreso.ChangeStatus(progreso.Value + 1, "Verificando " + TableLabel); connection.SetTableStructure(Tab); } //Ahora creo claves nuevas (deleteOnly = false) progreso.ChangeStatus("Estableciendo reglas de integridad"); try { connection.ExecuteNonQuery("FLUSH TABLES"); } catch { // No tengo permiso... no importa } connection.SetConstraints(Lfx.Workspace.Master.Structure.Constraints, false); if (omitPreAndPostSql == false) { progreso.ChangeStatus("Ejecutando guión posterior..."); InyectarSqlDesdeRecurso(connection, @"Data.Struct.db_upd_post.sql"); } if (MustEnableConstraints) { connection.EnableConstraints(true); } }
public CitiVentas(Lfx.Types.OperationProgress progreso) : base(progreso) { }
/// <summary> /// Descarga en caso de que haga falta algunos ensamblados necesarios para el funcionamiento del programa. /// </summary> private static void DescargarArchivosNecesarios() { IList<string> ArchivosNecesarios = new List<string>() { "Interop.WIA.dll", "MySql.Data.dll", "ICSharpCode.SharpZipLib.dll" }; IList<string> ArchivosFaltantes = new List<string>(); foreach (string Arch in ArchivosNecesarios) { if (System.IO.File.Exists(Arch) == false) ArchivosFaltantes.Add(Arch); } if (ArchivosFaltantes.Count > 0) { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Descargando archivos adicionales", "Se van a descargar algunos archivos necesarios para el funcionamiento de Lázaro"); Progreso.Max = ArchivosFaltantes.Count; Progreso.Begin(); bool CanWriteToAppFolder = Lfx.Environment.SystemInformation.CanWriteToAppFolder; using (WebClient Cliente = new WebClient()) { foreach (string Arch in ArchivosFaltantes) { Progreso.ChangeStatus("Descargando " + Arch); string ArchDestino; if (CanWriteToAppFolder) // Lo descargo directamente a la carpeta de la aplicación ArchDestino = Lfx.Environment.Folders.ApplicationFolder + Arch; else // Tengo UAC, lo descargo a la carpeta de actualizaciones y luego tengo que iniciar el ActualizadorLazaro.exe ArchDestino = Lfx.Environment.Folders.UpdatesFolder + Arch + ".new"; try { Cliente.DownloadFile(@"http://www.lazarogestion.com/aslnlwc/" + Arch, ArchDestino); } catch { // Nada } Progreso.Advance(1); } } Progreso.End(); if (CanWriteToAppFolder == false) Lfx.Environment.Shell.Reboot(); } }
public ArchivoSalidaVentas(Lfx.Types.OperationProgress progreso) : base(progreso) { }
public void ShowProgressRoutine(Lfx.Types.OperationProgress progreso) { this.BarraInferior.ShowProgressRoutine(progreso); }
public Lfx.Types.OperationResult Backup(BackupInfo backupInfo) { string WorkFolder = backupInfo.Name + System.IO.Path.DirectorySeparatorChar; Lfx.Environment.Folders.EnsurePathExists(this.BackupPath); if (!System.IO.Directory.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder)) { System.IO.Directory.CreateDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder); } Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Creando copia de seguridad", "Se está creando un volcado completo del almacén de datos en una carpeta, para resguardar."); Progreso.Modal = true; Progreso.Advertise = true; Progreso.Begin(); Progreso.Max = Lfx.Workspace.Master.Structure.Tables.Count + 1; Progreso.ChangeStatus("Exportando estructura"); Progreso.ChangeStatus(Progreso.Value + 1); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.AppendChild(Lfx.Workspace.Master.Structure.ToXml(doc)); doc.Save(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbstruct.xml"); BackupWriter Writer = new BackupWriter(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbdata.lbd"); Writer.Write(":BKP"); IList <string> TableList = Lfx.Data.DatabaseCache.DefaultCache.GetTableNames(); foreach (string Tabla in TableList) { string NombreTabla = Tabla; if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(Tabla)) { NombreTabla = Lfx.Workspace.Master.Structure.Tables[Tabla].Label; } Progreso.ChangeStatus("Volcando " + NombreTabla); Progreso.ChangeStatus(Progreso.Value + 1); ExportTableBin(Tabla, Writer); } Writer.Close(); System.IO.FileStream Archivo = new System.IO.FileStream(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "info.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write); using (System.IO.StreamWriter Escribidor = new System.IO.StreamWriter(Archivo, System.Text.Encoding.Default)) { Escribidor.WriteLine("Copia de seguridad de Lázaro"); Escribidor.WriteLine(""); Escribidor.WriteLine("Empresa=" + backupInfo.CompanyName); Escribidor.WriteLine("EspacioTrabajo=" + Lfx.Workspace.Master.Name); Escribidor.WriteLine("FechaYHora=" + System.DateTime.Now.ToString("dd-MM-yyyy") + " a las " + System.DateTime.Now.ToString("HH:mm:ss")); Escribidor.WriteLine("Usuario=" + backupInfo.UserName); Escribidor.WriteLine("Estación=" + Lfx.Environment.SystemInformation.MachineName); Escribidor.WriteLine("VersiónLazaro=" + backupInfo.ProgramVersion); Escribidor.WriteLine(""); Escribidor.WriteLine("Por favor no modifique ni elimine este archivo."); Escribidor.Close(); Archivo.Close(); } if (Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sistema.ComprimirCopiasDeSeguridad", 0) != 0) { Progreso.ChangeStatus("Comprimiendo los datos"); Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z"); ArchivoComprimido.Add(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "*"); if (System.IO.File.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z")) { Progreso.ChangeStatus("Eliminando archivos temporales"); // Borrar los archivos que acabo de comprimir System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.TemporaryFolder + WorkFolder); foreach (System.IO.FileInfo DirItem in Dir.GetFiles()) { if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt") { System.IO.File.Delete(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + DirItem.Name); } } } } Progreso.ChangeStatus("Almacenando"); Progreso.ChangeStatus(Progreso.Value + 1); Lfx.Environment.Folders.MoveDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder, this.BackupPath + WorkFolder); int GuardarBackups = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sisteam.Backup.CantMax", 14); if (GuardarBackups > 0) { List <BackupInfo> ListaDeBackups = this.GetBackups(); if (ListaDeBackups.Count > GuardarBackups) { Progreso.ChangeStatus("Eliminando copias de seguridad antiguas"); int BorrarBackups = ListaDeBackups.Count - GuardarBackups; if (BorrarBackups < ListaDeBackups.Count) { for (int i = 1; i <= BorrarBackups; i++) { this.Delete(this.GetOldestBackupName()); } } } } Progreso.End(); return(new Lfx.Types.SuccessOperationResult()); }
private void DetectarConfig() { if (this.ThreadBuscar != null) { this.ThreadBuscar.Abort(); this.ThreadBuscar = null; } switch (Lfx.Environment.SystemInformation.Platform) { case Lfx.Environment.SystemInformation.Platforms.Windows: Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Buscando un servidor", "Por favor aguarde mientras Lázaro busca un servidor en la red para utilizar como almacén de datos."); ProgresoBuscar.Visible = true; Progreso.Modal = false; Progreso.Advertise = false; Progreso.Begin(); System.Threading.ThreadStart Buscar = delegate { this.BuscarServidor(Progreso); }; this.ThreadBuscar = new System.Threading.Thread(Buscar); this.ThreadBuscar.IsBackground = true; this.ThreadBuscar.Start(); EtiquetaBuscarEspere.Visible = true; while (Progreso != null && Progreso.IsRunning) { System.Threading.Thread.Sleep(100); EtiquetaBuscando.Text = Progreso.Status; System.Windows.Forms.Application.DoEvents(); if (this.ThreadBuscar == null) return; } EtiquetaBuscarEspere.Visible = false; ProgresoBuscar.Visible = false; if (ServidorDetectado == null) { CheckInstalarAhora.Checked = true; EtiquetaBuscando.Text = "Lázaro no pudo encontrar un servidor SQL en la red. Si desea, puede instalar un servidor SQL en este equipo. Haga clic en 'Siguiente' para continuar."; } else { EtiquetaBuscando.Text = "Lázaro detectó un servidor SQL en la red. Haga clic en el botón 'Siguiente' para revisar la configuración detectada."; CheckOtroEquipo.Checked = true; EntradaServidor.Text = ServidorDetectado; } break; default: // No es Windows CheckInstalarAhora.Enabled = false; break; } }
public Archivo(Lfx.Types.OperationProgress progreso) : this() { this.Progreso = progreso; }
/// <summary> /// Prepara un servidor para ser utilizado por Lázaro. Crea estructuras y realiza una carga inicial de datos. /// </summary> /// <param name="progreso">El objeto OperationProgress donde notificar el progreso</param> public Lfx.Types.OperationResult Prepare(Lfx.Types.OperationProgress progreso) { bool MiProgreso = false; if (progreso == null) { progreso = new Types.OperationProgress("Preparando el almacén de datos", "Se están creando las tablas de datos y se va realizar una carga inicial de datos. Esta operación puede demorar varios minutos.") { Modal = true }; progreso.Begin(); MiProgreso = true; } // Creación de tablas progreso.ChangeStatus("Creando estructuras"); this.CheckAndUpdateDatabaseStructure(this.MasterConnection, true, progreso); this.MasterConnection.EnableConstraints(false); string Sql = ""; using (System.IO.Stream RecursoSql = ObtenerRecurso(@"Data.Struct.dbdata.sql")) { using (System.IO.StreamReader Lector = new System.IO.StreamReader(RecursoSql, System.Text.Encoding.UTF8)) { // Carga inicial de datos Sql = this.MasterConnection.CustomizeSql(Lector.ReadToEnd()); Lector.Close(); RecursoSql.Close(); } } // Si hay archivos adicionales de datos para la carga inicial, los incluyo // Estos suelen tener datos personalizados de esta instalación en partícular if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationFolder + "default.alf")) { using (System.IO.StreamReader Lector = new System.IO.StreamReader(Lfx.Environment.Folders.ApplicationFolder + "default.alf", System.Text.Encoding.UTF8)) { Sql += Lfx.Types.ControlChars.CrLf; Sql += this.MasterConnection.CustomizeSql(Lector.ReadToEnd()); Lector.Close(); } } progreso.ChangeStatus("Carga inicial de datos"); progreso.Max = Sql.Length; //this.MasterConnection.ExecuteSql(Sql); do { string Comando = Lfx.Data.Connection.GetNextCommand(ref Sql); try { this.MasterConnection.ExecuteNonQuery(Comando); } catch { // Hubo errores, pero continúo } progreso.ChangeStatus(progreso.Max - Sql.Length); }while (Sql.Length > 0); progreso.ChangeStatus("Carga de TagList"); // Cargar TagList y volver a verificar la estructura Lfx.Workspace.Master.Structure.TagList.Clear(); Lfx.Workspace.Master.Structure.LoadBuiltIn(); this.CheckAndUpdateDatabaseStructure(this.MasterConnection, false, progreso); this.MasterConnection.EnableConstraints(true); this.CurrentConfig.WriteGlobalSetting("Sistema.DB.Version", Lfx.Workspace.VersionUltima); if (MiProgreso) { progreso.End(); } return(new Lfx.Types.SuccessOperationResult()); }
public ArchivoSalidaConComprobantesFacturables(Lfx.Types.OperationProgress progreso) : base(progreso) { }
public override Lfx.Types.OperationResult Ok() { int PV = EntradaPV.ValueInt; int Desde = EntradaDesde.ValueInt; int Hasta = EntradaHasta.ValueInt; int Cantidad = Hasta - Desde + 1; Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulados, los comprobantes deberán ser archivados en todas sus copias y no podrán ser rehabilitados ni reutilizados.", "¿Está seguro de que desea anular " + Cantidad.ToString() + " comprobantes?"); Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; if (Pregunta.ShowDialog() == DialogResult.OK) { bool AnularPagos = EntradaAnularPagos.ValueInt != 0; int m_Id = 0; string IncluyeTipos = ""; switch (EntradaTipo.TextKey) { case "A": IncluyeTipos = "'FA', 'NCA', 'NDA'"; break; case "B": IncluyeTipos = "'FB', 'NCB', 'NDB'"; break; case "C": IncluyeTipos = "'FC', 'NCC', 'NDC'"; break; case "E": IncluyeTipos = "'FE', 'NCE', 'NDE'"; break; case "M": IncluyeTipos = "'FM', 'NCM', 'NDM'"; break; case "T": IncluyeTipos = "'T'"; break; default: IncluyeTipos = "'" + EntradaTipo.TextKey + "'"; break; } Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando comprobantes", "Se están anulando los comprobantes seleccionados."); Progreso.Cancelable = true; Progreso.Max = Cantidad; Progreso.Begin(); IDbTransaction Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable); for (int Numero = Desde; Numero <= Hasta; Numero++) { int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString()); if (IdFactura == 0) { // Es una factura que todava no existe // Tengo que crear la factura y anularla qGen.Insert InsertarComprob = new qGen.Insert("comprob"); InsertarComprob.Fields.AddWithValue("tipo_fac", "F" + EntradaTipo.TextKey); InsertarComprob.Fields.AddWithValue("id_formapago", 3); InsertarComprob.Fields.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual); InsertarComprob.Fields.AddWithValue("pv", Lfx.Types.Parsing.ParseInt(EntradaPV.Text)); InsertarComprob.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now); InsertarComprob.Fields.AddWithValue("id_vendedor", Lbl.Sys.Config.Actual.UsuarioConectado.Id); InsertarComprob.Fields.AddWithValue("id_cliente", Lbl.Sys.Config.Actual.UsuarioConectado.Id); InsertarComprob.Fields.AddWithValue("obs", "Comprobante anulado antes de ser impreso."); InsertarComprob.Fields.AddWithValue("impresa", 1); InsertarComprob.Fields.AddWithValue("anulada", 1); Connection.Execute(InsertarComprob); m_Id = Connection.FieldInt("SELECT LAST_INSERT_ID()"); Lbl.Comprobantes.ComprobanteConArticulos NuevoComprob = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, m_Id); NuevoComprob.Numerar(true); } else { Lbl.Comprobantes.ComprobanteConArticulos Fac = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdFactura); if (Fac.Anulado == false) Fac.Anular(AnularPagos); } Progreso.Advance(1); if (Progreso.Cancelar) break; } Progreso.End(); if (Progreso.Cancelar) { Trans.Rollback(); Lfx.Workspace.Master.RunTime.Toast("La operación fue cancelada.", "Aviso"); } else { Trans.Commit(); ProximosNumeros.Clear(); Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Recuerde archivar ambas copias.", "Aviso"); } EntradaDesde.ValueInt = 0; EntradaHasta.ValueInt = 0; EntradaDesde.Focus(); return base.Ok(); } else { return new Lfx.Types.FailureOperationResult("La operación fue cancelada."); } }
public void Restore(string backupName) { string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar; Lfx.Environment.Folders.EnsurePathExists(this.BackupPath); if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta)) { bool UsandoArchivoComprimido = false; Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa"); Progreso.Modal = true; /* Progreso.ChangeStatus("Descomprimiendo"); // Descomprimir backup si está comprimido if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) { Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z"); ArchivoComprimido.ExtractAll(BackupPath + Carpeta); UsandoArchivoComprimido = true; } */ Progreso.ChangeStatus("Eliminando datos actuales"); using (Lfx.Data.Connection DataBase = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad")) { Progreso.ChangeStatus("Acomodando estructuras"); Lfx.Workspace.Master.Structure.TagList.Clear(); Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml"); Lfx.Workspace.Master.CheckAndUpdateDataBaseVersion(true, true); using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd")) using (IDbTransaction Trans = DataBase.BeginTransaction()) { DataBase.EnableConstraints(false); Progreso.ChangeStatus("Incorporando tablas de datos"); Progreso.Max = (int)(Lector.Length / 1024); string TablaActual = null; string[] ListaCampos = null; object[] ValoresCampos = null; int CampoActual = 0; bool EndTable = false; qGen.BuilkInsert Insertador = new qGen.BuilkInsert(); do { string Comando = Lector.ReadString(4); switch (Comando) { case ":TBL": TablaActual = Lector.ReadPrefixedString4(); string NombreTabla; if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null) { NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label; } else { NombreTabla = TablaActual.ToTitleCase(); } EndTable = false; Progreso.ChangeStatus("Cargando " + NombreTabla); qGen.Delete DelCmd = new qGen.Delete(TablaActual); DelCmd.EnableDeleleteWithoutWhere = true; DataBase.Execute(DelCmd); break; case ":FDL": ListaCampos = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ValoresCampos = new object[ListaCampos.Length]; CampoActual = 0; break; case ":FLD": ValoresCampos[CampoActual++] = Lector.ReadField(); break; case ".ROW": qGen.Insert Insertar = new qGen.Insert(TablaActual); for (int i = 0; i < ListaCampos.Length; i++) { Insertar.Fields.AddWithValue(ListaCampos[i], ValoresCampos[i]); } Insertador.Add(Insertar); ValoresCampos = new object[ListaCampos.Length]; CampoActual = 0; break; case ":REM": Lector.ReadPrefixedString4(); break; case ".TBL": EndTable = true; break; } if (EndTable || Insertador.Count >= 1000) { if (Insertador.Count > 0) DataBase.Execute(Insertador); Insertador.Clear(); Progreso.Value = (int)(Lector.Position / 1024); } } while (Lector.Position < Lector.Length); Lector.Close(); if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql) { // PostgreSql: Tengo que actualizar las secuencias Progreso.ChangeStatus("Actualizando secuencias"); string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)"; foreach (string Tabla in Lfx.Data.DataBaseCache.DefaultCache.GetTableNames()) { string OID = DataBase.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'"); System.Data.DataTable Campos = DataBase.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"); foreach (System.Data.DataRow Campo in Campos.Rows) { if (Campo[2] != DBNull.Value && Campo[2] != null) { string DefaultCampo = System.Convert.ToString(Campo[2]); if (Regex.IsMatch(DefaultCampo, PatronSecuencia)) { string NombreCampo = System.Convert.ToString(Campo[0]); foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia)) { string Secuencia = Ocurrencia.Groups[1].ToString(); int MaxId = DataBase.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1; DataBase.ExecuteSql("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString()); } } } } } } if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst")) { // Incorporar Blobs Progreso.ChangeStatus("Incorporando imágenes"); System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default); string InfoImagen = null; do { InfoImagen = LectorBlobs.ReadLine(); if (InfoImagen != null && InfoImagen.Length > 0) { string Tabla = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string Campo = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string CampoId = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); // Guardar blob nuevo qGen.Update ActualizarBlob = new qGen.Update(DataBase, Tabla); ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId); System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1]; ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length)); ArchivoImagen.Close(); ActualizarBlob.Fields.AddWithValue(Campo, Contenido); DataBase.Execute(ActualizarBlob); } } while (InfoImagen != null); LectorBlobs.Close(); } if (UsandoArchivoComprimido) { Progreso.ChangeStatus("Eliminando archivos temporales"); // Borrar los archivos que descomprim temporalmente System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta); foreach (System.IO.FileInfo DirItem in Dir.GetFiles()) { if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt") { System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name); } } } Progreso.ChangeStatus("Terminando transacción"); Trans.Commit(); } Progreso.End(); } Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada"); } }
private void BotonPresentar_Click(object sender, EventArgs e) { if (Listado.CheckedItems.Count == 0) { Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para presentar.", "Acreditar"); return; } int CantidadCupones = 0; foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { CantidadCupones++; if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar") { Lui.Forms.MessageBox.Show("Sólo se pueden hacer presentaciones de cupones que no han sido presentados.", "Presentación de cupones"); return; } } } if (CantidadCupones == 0) { Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para presentar.", "Presentación de cupones"); return; } using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea marcar los cupones seleccionados como presentados?", "Presentación de cupones")) { Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; if (Pregunta.ShowDialog() == DialogResult.OK) { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Presentación de cupones", "Se están marcando los cupones seleccionados como 'Presentados'."); Progreso.Max = CantidadCupones; Progreso.Begin(); foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) { if (itm.Checked) { Progreso.Advance(1); Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text)); if (Cupon.Estado == 0) Cupon.Presentar(); } } Progreso.End(); this.RefreshList(); } } }
public Lfx.Types.OperationResult Backup(BackupInfo backupInfo) { string WorkFolder = backupInfo.Name + System.IO.Path.DirectorySeparatorChar; Lfx.Environment.Folders.EnsurePathExists(this.BackupPath); if (!System.IO.Directory.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder)) System.IO.Directory.CreateDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder); Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Creando copia de seguridad", "Se está creando un volcado completo del almacén de datos en una carpeta, para resguardar."); Progreso.Modal = true; Progreso.Advertise = true; Progreso.Begin(); Progreso.Max = Lfx.Workspace.Master.Structure.Tables.Count + 1; Progreso.ChangeStatus("Exportando estructura"); Progreso.ChangeStatus(Progreso.Value + 1); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.AppendChild(Lfx.Workspace.Master.Structure.ToXml(doc)); doc.Save(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbstruct.xml"); BackupWriter Writer = new BackupWriter(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbdata.lbd"); Writer.Write(":BKP"); IList<string> TableList = Lfx.Data.DataBaseCache.DefaultCache.GetTableNames(); foreach (string Tabla in TableList) { string NombreTabla = Tabla; if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(Tabla)) NombreTabla = Lfx.Workspace.Master.Structure.Tables[Tabla].Label; Progreso.ChangeStatus("Volcando " + NombreTabla); Progreso.ChangeStatus(Progreso.Value + 1); ExportTableBin(Tabla, Writer); } Writer.Close(); System.IO.FileStream Archivo = new System.IO.FileStream(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "info.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write); using (System.IO.StreamWriter Escribidor = new System.IO.StreamWriter(Archivo, System.Text.Encoding.Default)) { Escribidor.WriteLine("Copia de seguridad de Lázaro"); Escribidor.WriteLine(""); Escribidor.WriteLine("Empresa=" + backupInfo.CompanyName); Escribidor.WriteLine("EspacioTrabajo=" + Lfx.Workspace.Master.Name); Escribidor.WriteLine("FechaYHora=" + System.DateTime.Now.ToString("dd-MM-yyyy") + " a las " + System.DateTime.Now.ToString("HH:mm:ss")); Escribidor.WriteLine("Usuario=" + backupInfo.UserName); Escribidor.WriteLine("Estación=" + Lfx.Environment.SystemInformation.MachineName); Escribidor.WriteLine("VersiónLazaro=" + backupInfo.ProgramVersion); Escribidor.WriteLine(""); Escribidor.WriteLine("Por favor no modifique ni elimine este archivo."); Escribidor.Close(); Archivo.Close(); } if (Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<int>("Sistema.ComprimirCopiasDeSeguridad", 0) != 0) { Progreso.ChangeStatus("Comprimiendo los datos"); Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z"); ArchivoComprimido.Add(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "*"); if (System.IO.File.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z")) { Progreso.ChangeStatus("Eliminando archivos temporales"); // Borrar los archivos que acabo de comprimir System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.TemporaryFolder + WorkFolder); foreach (System.IO.FileInfo DirItem in Dir.GetFiles()) { if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt") { System.IO.File.Delete(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + DirItem.Name); } } } } Progreso.ChangeStatus("Almacenando"); Progreso.ChangeStatus(Progreso.Value + 1); Lfx.Environment.Folders.MoveDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder, this.BackupPath + WorkFolder); int GuardarBackups = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<int>("Sisteam.Backup.CantMax", 14); if (GuardarBackups > 0) { List<BackupInfo> ListaDeBackups = this.GetBackups(); if (ListaDeBackups.Count > GuardarBackups) { Progreso.ChangeStatus("Eliminando copias de seguridad antiguas"); int BorrarBackups = ListaDeBackups.Count - GuardarBackups; if (BorrarBackups < ListaDeBackups.Count) { for (int i = 1; i <= BorrarBackups; i++) { this.Delete(this.GetOldestBackupName()); } } } } Progreso.End(); return new Lfx.Types.SuccessOperationResult(); }
public override Lfx.Types.OperationResult Ok() { int PV = EntradaPV.ValueInt; int Desde = EntradaDesde.ValueInt; int Hasta = EntradaHasta.ValueInt; int Cantidad = Hasta - Desde + 1; Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulados, los comprobantes deberán ser archivados en todas sus copias y no podrán ser rehabilitados ni reutilizados.", "¿Está seguro de que desea anular " + Cantidad.ToString() + " comprobantes?"); Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo; if (Pregunta.ShowDialog() == DialogResult.OK) { bool AnularPagos = EntradaAnularPagos.ValueInt != 0; int m_Id = 0; string IncluyeTipos = ""; switch (EntradaTipo.TextKey) { case "A": IncluyeTipos = "'FA', 'NCA', 'NDA'"; break; case "B": IncluyeTipos = "'FB', 'NCB', 'NDB'"; break; case "C": IncluyeTipos = "'FC', 'NCC', 'NDC'"; break; case "E": IncluyeTipos = "'FE', 'NCE', 'NDE'"; break; case "M": IncluyeTipos = "'FM', 'NCM', 'NDM'"; break; case "T": IncluyeTipos = "'T'"; break; default: IncluyeTipos = "'" + EntradaTipo.TextKey + "'"; break; } Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando comprobantes", "Se están anulando los comprobantes seleccionados."); Progreso.Cancelable = true; Progreso.Max = Cantidad; Progreso.Begin(); IDbTransaction Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable); for (int Numero = Desde; Numero <= Hasta; Numero++) { int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString() + " ORDER BY anulada"); if (IdFactura == 0) { // Es una factura que todava no existe // Tengo que crear la factura y anularla qGen.Insert InsertarComprob = new qGen.Insert("comprob"); InsertarComprob.ColumnValues.AddWithValue("tipo_fac", "F" + EntradaTipo.TextKey); InsertarComprob.ColumnValues.AddWithValue("id_formapago", 3); InsertarComprob.ColumnValues.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual); InsertarComprob.ColumnValues.AddWithValue("pv", Lfx.Types.Parsing.ParseInt(EntradaPV.Text)); InsertarComprob.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()")); InsertarComprob.ColumnValues.AddWithValue("id_vendedor", Lbl.Sys.Config.Actual.UsuarioConectado.Id); InsertarComprob.ColumnValues.AddWithValue("id_cliente", Lbl.Sys.Config.Actual.UsuarioConectado.Id); InsertarComprob.ColumnValues.AddWithValue("obs", "Comprobante anulado antes de ser impreso."); InsertarComprob.ColumnValues.AddWithValue("impresa", 1); InsertarComprob.ColumnValues.AddWithValue("anulada", 1); Connection.ExecuteNonQuery(InsertarComprob); m_Id = Connection.FieldInt("SELECT LAST_INSERT_ID()"); Lbl.Comprobantes.ComprobanteConArticulos NuevoComprob = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, m_Id); new Lbl.Comprobantes.Numerador(NuevoComprob).Numerar(true); } else { Lbl.Comprobantes.ComprobanteConArticulos Fac = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdFactura); if (Fac.Anulado == false) { Fac.Anular(AnularPagos); } } Progreso.Advance(1); if (Progreso.Cancelar) { break; } } Progreso.End(); if (Progreso.Cancelar) { Trans.Rollback(); Lfx.Workspace.Master.RunTime.Toast("La operación fue cancelada.", "Aviso"); } else { Trans.Commit(); ProximosNumeros.Clear(); if (this.DeCompra) { Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Si fueron anulados por error de carga, ahora puede cargarlos nuevamente.", "Aviso"); } else { Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Recuerde archivar ambas copias.", "Aviso"); } } EntradaDesde.ValueInt = 0; EntradaHasta.ValueInt = 0; EntradaDesde.Focus(); return(base.Ok()); } else { return(new Lfx.Types.FailureOperationResult("La operación fue cancelada.")); } }
private void ProcesarReimpresion(string tipo, int pv, int desde, int hasta) { using (Lfx.Data.Connection Conn = Lfx.Workspace.Master.GetNewConnection("Reimpresión de comprobantes")) { int Cantidad = Math.Abs(hasta - desde); Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Reimprimiendo", "Se están reimprimiendo " + Cantidad.ToString() + " comprobantes."); Progreso.Cancelable = true; Progreso.Max = Cantidad; Progreso.Modal = true; Progreso.Advertise = true; Progreso.Begin(); string IncluyeTipos = ""; switch (tipo) { case "A": IncluyeTipos = "'FA', 'NCA', 'NDA'"; break; case "B": IncluyeTipos = "'FB', 'NCB', 'NDB'"; break; case "C": IncluyeTipos = "'FC', 'NCC', 'NDC'"; break; case "E": IncluyeTipos = "'FE', 'NCE', 'NDE'"; break; case "M": IncluyeTipos = "'FM', 'NCM', 'NDM'"; break; default: IncluyeTipos = "'" + EntradaTipo.TextKey + "'"; break; } int Paso = desde < hasta ? 1 : -1; for (int Numero = desde; Numero != hasta; Numero += Paso) { int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND anulada=0 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + pv.ToString() + " AND numero=" + Numero.ToString()); if (IdFactura == 0) { // No existe, supongo que está anulado, lo salteo } else { Lbl.Comprobantes.ComprobanteFacturable Fac = new Lbl.Comprobantes.ComprobanteFacturable(Conn, IdFactura); Progreso.ChangeStatus("Imprimiendo " + Fac.ToString()); Lazaro.Impresion.Comprobantes.ImpresorComprobanteConArticulos Impr = new Lazaro.Impresion.Comprobantes.ImpresorComprobanteConArticulos(Fac, null); Impr.Imprimir(); } Progreso.Advance(1); if (Progreso.Cancelar) break; } Progreso.End(); } }
/// <summary> /// Recalcula completamente el saldo de la caja, para corregir errores de transporte. Principalmente de uso interno. /// </summary> public void Recalcular() { Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la caja " + this.ToString()); Progreso.Begin(); System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM cajas_movim WHERE id_caja=" + this.Id.ToString() + " ORDER BY id_movim"); decimal Saldo = 0; Progreso.Max = Movims.Rows.Count; foreach (System.Data.DataRow Movim in Movims.Rows) { Saldo += System.Convert.ToDecimal(Movim["importe"]); qGen.Update Upd = new qGen.Update("cajas_movim"); Upd.Fields.AddWithValue("saldo", Saldo); Upd.WhereClause = new qGen.Where("id_movim", System.Convert.ToInt32(Movim["id_movim"])); this.Connection.Execute(Upd); Progreso.Advance(1); } Progreso.End(); }
public void Restore(string backupName) { string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar; Lfx.Environment.Folders.EnsurePathExists(this.BackupPath); if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta)) { bool UsandoArchivoComprimido = false; Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa"); Progreso.Modal = true; /* Progreso.ChangeStatus("Descomprimiendo"); * // Descomprimir backup si está comprimido * if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) { * Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z"); * ArchivoComprimido.ExtractAll(BackupPath + Carpeta); * UsandoArchivoComprimido = true; * } */ Progreso.ChangeStatus("Eliminando datos actuales"); using (Lfx.Data.IConnection ConnRestaurar = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad") as Lfx.Data.IConnection) { Progreso.ChangeStatus("Acomodando estructuras"); Lfx.Workspace.Master.Structure.TagList.Clear(); Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml"); //Lfx.Workspace.Master.CheckAndUpdateDatabaseVersion(true, true); using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd")) using (IDbTransaction Trans = ConnRestaurar.BeginTransaction()) { ConnRestaurar.EnableConstraints(false); Progreso.ChangeStatus("Incorporando tablas de datos"); Progreso.Max = (int)(Lector.Length / 1024); string TablaActual = null; string[] ListaCampos = null; object[] ValoresCampos = null; int CampoActual = 0; bool EndTable = false; qGen.BuilkInsert Insertador = new qGen.BuilkInsert(); do { string Comando = Lector.ReadString(4); switch (Comando) { case ":TBL": TablaActual = Lector.ReadPrefixedString4(); string NombreTabla; if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null) { NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label; } else { NombreTabla = TablaActual.ToTitleCase(); } EndTable = false; Progreso.ChangeStatus("Cargando " + NombreTabla); qGen.Delete DelCmd = new qGen.Delete(TablaActual); DelCmd.EnableDeleleteWithoutWhere = true; ConnRestaurar.ExecuteNonQuery(DelCmd); break; case ":FDL": ListaCampos = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ValoresCampos = new object[ListaCampos.Length]; CampoActual = 0; break; case ":FLD": ValoresCampos[CampoActual++] = Lector.ReadField(); break; case ".ROW": qGen.Insert Insertar = new qGen.Insert(TablaActual); for (int i = 0; i < ListaCampos.Length; i++) { Insertar.ColumnValues.AddWithValue(ListaCampos[i], ValoresCampos[i]); } Insertador.Add(Insertar); ValoresCampos = new object[ListaCampos.Length]; CampoActual = 0; break; case ":REM": Lector.ReadPrefixedString4(); break; case ".TBL": EndTable = true; break; } if (EndTable || Insertador.Count >= 1000) { if (Insertador.Count > 0) { ConnRestaurar.ExecuteNonQuery(Insertador); } Insertador.Clear(); Progreso.Value = (int)(Lector.Position / 1024); } } while (Lector.Position < Lector.Length); Lector.Close(); if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql) { // PostgreSql: Tengo que actualizar las secuencias Progreso.ChangeStatus("Actualizando secuencias"); string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)"; foreach (string Tabla in Lfx.Data.DatabaseCache.DefaultCache.GetTableNames()) { string OID = ConnRestaurar.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'"); System.Data.DataTable Campos = ConnRestaurar.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"); foreach (System.Data.DataRow Campo in Campos.Rows) { if (Campo[2] != DBNull.Value && Campo[2] != null) { string DefaultCampo = System.Convert.ToString(Campo[2]); if (Regex.IsMatch(DefaultCampo, PatronSecuencia)) { string NombreCampo = System.Convert.ToString(Campo[0]); foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia)) { string Secuencia = Ocurrencia.Groups[1].ToString(); int MaxId = ConnRestaurar.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1; ConnRestaurar.ExecuteNonQuery("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString()); } } } } } } if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst")) { // Incorporar Blobs Progreso.ChangeStatus("Incorporando imágenes"); System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default); string InfoImagen = null; do { InfoImagen = LectorBlobs.ReadLine(); if (InfoImagen != null && InfoImagen.Length > 0) { string Tabla = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string Campo = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string CampoId = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ","); // Guardar blob nuevo qGen.Update ActualizarBlob = new qGen.Update(Tabla); ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId); System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1]; ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length)); ArchivoImagen.Close(); ActualizarBlob.ColumnValues.AddWithValue(Campo, Contenido); ConnRestaurar.ExecuteNonQuery(ActualizarBlob); } }while (InfoImagen != null); LectorBlobs.Close(); } if (UsandoArchivoComprimido) { Progreso.ChangeStatus("Eliminando archivos temporales"); // Borrar los archivos que descomprim temporalmente System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta); foreach (System.IO.FileInfo DirItem in Dir.GetFiles()) { if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt") { System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name); } } } Progreso.ChangeStatus("Terminando transacción"); Trans.Commit(); } Progreso.End(); } Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada"); } }