Exemple #1
0
                public static int Main(string[] args)
                {
                        System.Threading.Thread.CurrentThread.Name = "Lazaro";

                        bool ReconfigDB = false, DebugMode = false, TraceMode = false, IgnoreUpdates = false;
                        bool MostrarAsistenteConfig = false, ClearCache = false;

                        string NombreConfig = "default";

                        if (args != null) {
                                foreach (string Argumento in args) {
                                        switch (Argumento) {
                                                case "/config":
                                                case "--config":
                                                        ReconfigDB = true;
                                                        break;

                                                case "/wizard":
                                                case "--wizard":
                                                        MostrarAsistenteConfig = true;
                                                        break;

                                                case "/ignoreupdates":
                                                case "--ignoreupdates":
                                                        IgnoreUpdates = true;
                                                        break;

                                                case "/clearcache":
                                                case "--clearcache":
                                                        ClearCache = true;
                                                        break;

                                                case "/help":
                                                case "--help":
                                                case "/?":
                                                        if (Lfx.Environment.SystemInformation.Platform == Lfx.Environment.SystemInformation.Platforms.Windows)
                                                                System.Windows.Forms.MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + @" [/config] [/ignoreupdates] [/debug] [/clearcache] [/ignoreupdates] [EspacioTrabajo]", "Ayuda");
                                                        else
                                                                System.Windows.Forms.MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + @" [--config] [--ignoreupdates] [--debug] [--clearcache] [--ignoreupdates] [EspacioTrabajo]", "Ayuda");
                                                        System.Environment.Exit(0);
                                                        break;

                                                case "/debug":
                                                case "--debug":
                                                        DebugMode = true;
                                                        IgnoreUpdates = true;
                                                        break;

                                                case "/trace":
                                                case "--trace":
                                                        TraceMode = true;
                                                        break;

                                                case "/portable":
                                                case "--portable":
                                                        Lfx.Environment.Folders.PortableMode = true;
                                                        break;

                                                default:
                                                        NombreConfig = System.IO.Path.GetFileNameWithoutExtension(Argumento);
                                                        break;
                                        }
                                }
                        }


                        try {
                                Lfx.Environment.Folders.EnsurePathExists(Lfx.Environment.Folders.ApplicationFolder);
                        } catch (Exception ex) {
                                Lui.Forms.MessageBox.Show("No se puede crear la carpeta " + Lfx.Environment.Folders.ApplicationFolder + ". " + ex.Message, "Error");
                        }
                        try {
                                Lfx.Environment.Folders.EnsurePathExists(Lfx.Environment.Folders.ApplicationDataFolder);
                        } catch (Exception ex) {
                                Lui.Forms.MessageBox.Show("No se puede crear la carpeta " + Lfx.Environment.Folders.ApplicationDataFolder + ". " + ex.Message, "Error");
                        }

                        if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationFolder + "portable.lwf")) {
                                NombreConfig = "portable";
                                Lfx.Environment.Folders.PortableMode = true;
                        }


                        // Manejadores de excepciones
                        Application.EnableVisualStyles();
                        if (DebugMode == false) {
                                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ThreadExceptionHandler);
                                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(GlobalExceptionHandler);
                                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                        }

                        if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationDataFolder + "clear.txt"))
                                ClearCache = true;


                        // Busco actualización en la caché
                        if (ClearCache) {
                                try {
                                        Lfx.Environment.Folders.DeleteWithWildcards(Lfx.Environment.Folders.TemporaryFolder, "*.*");
                                } catch {
                                        // Si algún archivo no se puede borrar, no importa
                                }

                                try {
                                        Lfx.Environment.Folders.DeleteWithWildcards(Lfx.Environment.Folders.UpdatesFolder, "*.*");
                                        Lfx.Environment.Folders.DeleteWithWildcards(Lfx.Environment.Folders.UpdatesFolder + "Components" + System.IO.Path.DirectorySeparatorChar, "*.*");
                                } catch {
                                        // Si algún archivo no se puede borrar, no importa
                                }

                                try {
                                        Lfx.Environment.Folders.DeleteWithWildcards(Lfx.Environment.Folders.ApplicationDataFolder, "clear.txt");
                                } catch {
                                        // Si algún archivo no se puede borrar, no importa
                                }

                        }

                        // Verifico estar utilizando un Encoding compatible (ISO-8859-1 o UTF-8)
                        if (System.Text.Encoding.Default.BodyName != "iso-8859-1"
                                && System.Text.Encoding.Default.BodyName != "utf-8") {
                                System.Windows.Forms.MessageBox.Show("La códificación " + System.Text.Encoding.Default.BodyName.ToUpperInvariant() + " no es válida. Sólo se permiten las codificaciones ISO-8859-1 (Latin-1) y UTF-8.", "Error");
                                System.Windows.Forms.Application.Exit();
                        }


                        if (IgnoreUpdates == false && System.IO.Directory.Exists(Lfx.Environment.Folders.UpdatesFolder)) {
                                // Si hay actualizaciones pendientes, reinicio para que ActualizadorLazaro se encargue de ellas.
                                string[] ArchivosNuevos = System.IO.Directory.GetFiles(Lfx.Environment.Folders.UpdatesFolder, "*.new", System.IO.SearchOption.AllDirectories);
                                if (ArchivosNuevos.Length > 0) {
                                        System.Console.WriteLine("Existen actualizaciones pendientes. Ejecutando ActualizadorLazaro");
                                        if (Lfx.Environment.SystemInformation.IsUacActive)
                                                Lui.Forms.MessageBox.Show("Lázaro se va a actualizar ahora. Es probable que el sistema le solicite autorización durante la actualización.", "Lázaro");
                                        Lfx.Environment.Shell.Reboot();
                                }
                        }


                        DescargarArchivosNecesarios();

                        //Si no hay espacio de trabajo predeterminado (default.lwf), presento una ventana de selección
                        System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.ApplicationDataFolder);
                        if (Dir.GetFiles(NombreConfig + ".lwf").Length == 0 && Dir.GetFiles("*.lwf").Length >= 1) {
                                using (Lui.Forms.WorkspaceSelectorForm SelectEspacio = new Lui.Forms.WorkspaceSelectorForm()) {
                                        if (SelectEspacio.ShowDialog() == DialogResult.OK) {
                                                NombreConfig = SelectEspacio.WorkspaceName;
                                                if (NombreConfig == null)
                                                        System.Environment.Exit(0);
                                        } else {
                                                System.Environment.Exit(0);
                                        }
                                }
                        }

                        // Inicio el espacio de trabajo
                        Lfx.Workspace.Master = new Lfx.Workspace(NombreConfig, false, false);
                        Lfx.Workspace.Master.DebugMode = DebugMode;
                        Lfx.Workspace.Master.TraceMode = TraceMode;
                        Lfx.Workspace.Master.RunTime.IpcEvent += new Lfx.RunTimeServices.IpcEventHandler(Workspace_IpcEvent);

                        // Asigno a la aplicación WinForms la misma cultura que se está usando en el espacio de trabajo
                        System.Windows.Forms.Application.CurrentCulture = Lfx.Workspace.Master.CultureInfo;

                        // Si no hay datos de configuración, voy a presentar el asistente
                        if (Lfx.Workspace.Master.CurrentConfig.ReadLocalSettingString("Data", "DataSource", null) == null)
                                MostrarAsistenteConfig = true;

                        if (MostrarAsistenteConfig || ReconfigDB) {
                                // Presento el asistente de configurar almacén de datos
                                using (Config.Inicial AsistenteInicial = new Config.Inicial()) {
                                        if (AsistenteInicial.ShowDialog() == DialogResult.Cancel)
                                                System.Environment.Exit(0);
                                }
                        }

                        IniciarDatos();

                        Lfx.Workspace.Master.InitUpdater();

                        CargarComponentes();

                        if (IgnoreUpdates == false) {
                                // Verifico la versión de Lázaro requerida por la BD
                                DateTime FechaLazaroExe = System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location);
                                DateTime MinVersion = DateTime.ParseExact(Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.DB.VersionMinima", "2000-01-01 00:00:00"), Lfx.Types.Formatting.DateTime.SqlDateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
                                if (FechaLazaroExe < MinVersion) {
                                        Misc.ActualizarAhora Act = new Misc.ActualizarAhora();
                                        DialogResult Res = Act.ShowDialog();
                                        switch (Res) {
                                                case DialogResult.OK:
                                                        Lfx.Environment.Shell.Reboot();
                                                        break;
                                                default:
                                                        Lfx.Workspace.Master.RunTime.Toast("La versión de Lázaro que está utilizando es demasiado antigua. Descargue e instale la última versión para continuar. Si desea más información ingrese a la página web www.lazarogestion.com", "Toast");
                                                        break;
                                        }
                                        System.Environment.Exit(1);
                                } else {
                                        // Cumple con la versión requerida, pero de todos modos verifico si es necesario actualizar Lázaro
                                        DateTime VersionEstructura = DateTime.ParseExact(Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.DB.VersionEstructura", "2000-01-01 00:00:00"), Lfx.Types.Formatting.DateTime.SqlDateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
                                        TimeSpan Diferencia = FechaLazaroExe - VersionEstructura;

                                        if (Diferencia.TotalHours < -12) {
                                                // Lázaro es más viejo que la bd por al menos 12 horas
                                                Misc.ActualizarAhora Act = new Misc.ActualizarAhora();
                                                DialogResult Res = Act.ShowDialog();
                                                switch (Res) {
                                                        case DialogResult.OK:
                                                                Lfx.Environment.Shell.Reboot();
                                                                break;
                                                        default:
                                                                Lfx.Workspace.Master.RunTime.Toast("La versión de Lázaro que está utilizando es antigua. Es recomendable que descargue e instale la última versión.", "Aviso");
                                                                break;
                                                }
                                        }
                                }
                        }

                        if (Lfx.Environment.SystemInformation.DesignMode == false) {
                                // Si es necesario, actualizo la estructura de la base de datos
                                Lfx.Workspace.Master.CheckAndUpdateDataBaseVersion(false, false);
                        }

                        Lfx.Types.OperationResult ResultadoInicio = IniciarGui();

                        if (ResultadoInicio.Success == false)
                                Lui.Forms.MessageBox.Show(ResultadoInicio.Message, "Error al Iniciar");

                        return 0;
                }
Exemple #2
0
                /// <summary>
                /// Inicia el acceso al almacén de datos.
                /// </summary>
                private static void IniciarDatos()
                {
                        do {
                                Lfx.Types.OperationResult Res = AbrirConexion();

                                // Si no pudo conectar, muestro la configuración de la base de datos
                                // Si hay DSN, muestro el error
                                if (Res.Success == false) {
                                        bool MostrarConfig = true;

                                        if (Lfx.Workspace.Master.CurrentConfig.ReadLocalSettingString("Data", "DataSource", null) != null) {
                                                using (Config.ErrorConexion FormError = new Config.ErrorConexion()) {
                                                        if (Res.Message.IndexOf("Unable to connect to any of the specified MySQL hosts") >= 0) {
                                                                if (Lfx.Data.DataBaseCache.DefaultCache.ServerName.ToLowerInvariant() == "localhost") {
                                                                        string TipoServidor = "";
                                                                        switch (Lfx.Data.DataBaseCache.DefaultCache.AccessMode) {
                                                                                case Lfx.Data.AccessModes.MySql:
                                                                                        TipoServidor = "MariaDB/MySQL";
                                                                                        break;
                                                                                case Lfx.Data.AccessModes.MSSql:
                                                                                        TipoServidor = "SQL Server";
                                                                                        break;
                                                                                case Lfx.Data.AccessModes.Npgsql:
                                                                                        TipoServidor = "PostgreSQL";
                                                                                        break;
                                                                                case Lfx.Data.AccessModes.Oracle:
                                                                                        TipoServidor = "Oracle";
                                                                                        break;
                                                                        }
                                                                        FormError.Ayuda = @"No se puede conectar con el servidor local. Verifique que el servidor " + TipoServidor + @" se encuentra instalado y funcionando en el equipo.
Si necesita información sobre cómo instalar o configurar un servidor SQL para Lázaro, consulte la ayuda en línea en www.lazarogestion.com";
                                                                } else {
                                                                        FormError.Ayuda = "No se puede conectar con el servidor remoto. Verifique que el servidor en el equipo remoto '" + Lfx.Data.DataBaseCache.DefaultCache.ServerName + @"' se encuentre funcionando y que su conexión de red esté activa.";
                                                                }
                                                        } else if (Res.Message.IndexOf("Access denied for user") >= 0) {
                                                                FormError.Ayuda = "El servidor impidió el acceso debido a que el nombre de usuario o la contraseña son incorrectos. Haga clic en 'Configurarción' y luego en 'Configuración avanzada' y verifique la configuración proporcionada.";
                                                        } else if (Res.Message.IndexOf("Debe preparar el almacén") >= 0) {
                                                                FormError.Ayuda = "Debe preparar el servidor SQL para que Lázaro pueda utilizarlo como almacén de datos.";
                                                        } else {
                                                                FormError.Ayuda = "No se dispone de información extendida sobre el error. Por favor lea el mensaje de error original a continuación:";
                                                        }

                                                        FormError.ErrorOriginal = Res.Message;

                                                        switch (FormError.ShowDialog()) {
                                                                case DialogResult.Cancel:
                                                                        MostrarConfig = false;
                                                                        System.Environment.Exit(0);
                                                                        break;

                                                                case DialogResult.Retry:
                                                                        MostrarConfig = false;
                                                                        break;

                                                                case DialogResult.Yes:
                                                                        MostrarConfig = true;
                                                                        break;
                                                        }
                                                }
                                        }

                                        if (MostrarConfig) {
                                                using (Config.Inicial ConfigBD = new Config.Inicial()) {
                                                        if (ConfigBD.ShowDialog() == DialogResult.Cancel) {
                                                                MostrarConfig = false;
                                                                System.Environment.Exit(0);
                                                        }
                                                }
                                        }
                                } else {
                                        break;
                                }
                        } while (true);

                        // Habilito el gestor de configuración
                        Lbl.Sys.Config.Actual = new Lbl.Sys.Configuracion.Global();
                        Lbl.Sys.Config.Cargar();

                        // Habilito la recuperación de conexiones
                        Lfx.Workspace.Master.MasterConnection.EnableRecover = true;
                }