//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /// <summary> /// Returns a valid Display Object from Pos Settings or Null /// </summary> /// <returns></returns> public static object InitDisplay() { object result = null; bool hardwareDisplayEnabled = Convert.ToBoolean(GlobalFramework.Settings["hardwareDisplayEnabled"]); if (hardwareDisplayEnabled) { string hardwareDisplayVID = GlobalFramework.Settings["hardwareDisplayVID"]; string hardwareDisplayPID = GlobalFramework.Settings["hardwareDisplayPID"]; string hardwareDisplayEndPoint = GlobalFramework.Settings["hardwareDisplayEndPoint"]; string hardwareDisplayCodeTable = GlobalFramework.Settings["hardwareDisplayCodeTable"]; int hardwareDisplayCharactersPerLine = Convert.ToUInt16(GlobalFramework.Settings["hardwareDisplayCharactersPerLine"]); uint hardwareDisplayGoToStandByInSeconds = Convert.ToUInt16(GlobalFramework.Settings["hardwareDisplayGoToStandByInSeconds"]); string hardwareDisplayStandByLine1 = GlobalFramework.Settings["hardwareDisplayStandByLine1"]; string hardwareDisplayStandByLine2 = GlobalFramework.Settings["hardwareDisplayStandByLine2"]; //Init UsbDisplayDevice displayDevice = new UsbDisplayDevice( hardwareDisplayVID, hardwareDisplayPID, hardwareDisplayEndPoint ); //Initializers displayDevice._charactersPerLine = hardwareDisplayCharactersPerLine; displayDevice._standByInSeconds = hardwareDisplayGoToStandByInSeconds; displayDevice._standByLine1 = hardwareDisplayStandByLine1; displayDevice._standByLine2 = hardwareDisplayStandByLine2; result = displayDevice; } return(result); }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: private void Init() { try { //Used to Force create DatabaseScema and Fixtures with XPO (Non Script Mode): Requirements for Work: Empty or Non Exist Database //Notes: OnError "An exception of type 'DevExpress.Xpo.DB.Exceptions.SchemaCorrectionNeededException'", UnCheck [X] Break when this exception is user-unhandled and continue, watch log and wait until sucefull message appear bool xpoCreateDatabaseAndSchema = SettingsApp.XPOCreateDatabaseAndSchema; bool xpoCreateDatabaseObjectsWithFixtures = xpoCreateDatabaseAndSchema; //Prepare AutoCreateOption AutoCreateOption xpoAutoCreateOption = (xpoCreateDatabaseAndSchema) ? AutoCreateOption.DatabaseAndSchema : AutoCreateOption.None; //Init Settings Main Config Settings //GlobalFramework.Settings = ConfigurationManager.AppSettings; //Override Licence data with Encrypted File Data if (File.Exists(SettingsApp.LicenceFileName)) { Utils.AssignLicence(SettingsApp.LicenceFileName, true); } //Other Global App Settings GlobalApp.MultiUserEnvironment = Convert.ToBoolean(GlobalFramework.Settings["appMultiUserEnvironment"]); GlobalApp.UseVirtualKeyBoard = Convert.ToBoolean(GlobalFramework.Settings["useVirtualKeyBoard"]); //Init App Notifications GlobalApp.Notifications = new System.Collections.Generic.Dictionary <string, bool>(); GlobalApp.Notifications["SHOW_PRINTER_UNDEFINED"] = true; //System GlobalApp.FilePickerStartPath = System.IO.Directory.GetCurrentDirectory(); //Get DataBase Details GlobalFramework.DatabaseType = (DatabaseType)Enum.Parse(typeof(DatabaseType), GlobalFramework.Settings["databaseType"]); //Override default Database name with parameter from config string configDatabaseName = GlobalFramework.Settings["databaseName"]; GlobalFramework.DatabaseName = (string.IsNullOrEmpty(configDatabaseName)) ? SettingsApp.DatabaseName : configDatabaseName; //Xpo Connection String string xpoConnectionString = string.Format(GlobalFramework.Settings["xpoConnectionString"], GlobalFramework.DatabaseName.ToLower()); Utils.AssignConnectionStringToSettings(xpoConnectionString); //Removed Protected Files //ProtectedFiles, Before Create Database from Scripts, usefull if Scripts are modified by User if (SettingsApp.ProtectedFilesUse) { GlobalApp.ProtectedFiles = InitProtectedFiles(); } //Check if Database Exists if Not Create it from Scripts bool databaseCreated = false; if (!xpoCreateDatabaseAndSchema) { //Get result to check if DB is created (true) try { // Launch Scripts databaseCreated = DataLayer.CreateDatabaseSchema(xpoConnectionString, GlobalFramework.DatabaseType, GlobalFramework.DatabaseName); } catch (Exception ex) { //Extra protection to prevent goes to login without a valid connection _log.Error(ex.Message, ex); Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, Resx.global_error, ex.Message); Environment.Exit(0); } } //Init XPO Connector DataLayer try { _log.Debug(string.Format("Init XpoDefault.DataLayer: [{0}]", xpoConnectionString)); XpoDefault.DataLayer = XpoDefault.GetDataLayer(xpoConnectionString, xpoAutoCreateOption); GlobalFramework.SessionXpo = new Session(XpoDefault.DataLayer) { LockingOption = LockingOption.None }; } catch (Exception ex) { _log.Error(ex.Message, ex); Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, Resx.global_error, ex.Message); throw; } //Check Valid Database Scheme if (!xpoCreateDatabaseAndSchema && !FrameworkUtils.IsRunningOnMono()) { bool isSchemaValid = DataLayer.IsSchemaValid(xpoConnectionString); _log.Debug(string.Format("Check if Database Scheme: isSchemaValid : [{0}]", isSchemaValid)); if (!isSchemaValid) { string endMessage = "Invalid database Schema! Fix database Schema and Try Again!"; Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(500, 300), MessageType.Error, ButtonsType.Ok, Resx.global_error, string.Format(endMessage, Environment.NewLine)); Environment.Exit(0); } } // Assign PluginSoftwareVendor Reference to DataLayer SettingsApp to use In Date Protection, we Required to assign it Statically to Prevent Circular References // Required to be here, before it is used in above lines, ex Utils.GetTerminal() if (GlobalFramework.PluginSoftwareVendor != null) { logicpos.datalayer.App.SettingsApp.PluginSoftwareVendor = GlobalFramework.PluginSoftwareVendor; } //If not in Xpo create database Scheme Mode, Get Terminal from Db if (!xpoCreateDatabaseAndSchema) { GlobalFramework.LoggedTerminal = Utils.GetTerminal(); } //After Assigned LoggedUser if (xpoCreateDatabaseObjectsWithFixtures) { InitFixtures.InitUserAndTerminal(GlobalFramework.SessionXpo); InitFixtures.InitOther(GlobalFramework.SessionXpo); InitFixtures.InitDocumentFinance(GlobalFramework.SessionXpo); InitFixtures.InitWorkSession(GlobalFramework.SessionXpo); } //End Xpo Create Scheme and Fixtures, Terminate App and Request assign False to Developer Vars if (xpoCreateDatabaseAndSchema) { string endMessage = "Xpo Create Schema and Fixtures Done!{0}Please assign false to 'xpoCreateDatabaseAndSchema' and 'xpoCreateDatabaseObjectsWithFixtures' and run App again"; Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(500, 300), MessageType.Info, ButtonsType.Ok, Resx.global_information, string.Format(endMessage, Environment.NewLine)); Environment.Exit(0); } //Init PreferenceParameters GlobalFramework.PreferenceParameters = FrameworkUtils.GetPreferencesParameters(); //Init Preferences Path MainApp.InitPathsPrefs(); bool validDirectoryBackup = FrameworkUtils.CreateDirectory(FrameworkUtils.OSSlash(Convert.ToString(GlobalFramework.Path["backups"]))); //Show Dialog if Cant Create Backups Directory (Extra Protection for Shared Network Folders) if (!validDirectoryBackup) { ResponseType response = Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, Resx.global_error, string.Format(Resx.dialog_message_error_create_directory_backups, Convert.ToString(GlobalFramework.Path["backups"]))); //Enable Quit After BootStrap, Preventing Application.Run() if (response == ResponseType.No) { _quitAfterBootStrap = true; } } //CultureInfo/Localization string culture = GlobalFramework.PreferenceParameters["CULTURE"]; if (!string.IsNullOrEmpty(culture)) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture); } GlobalFramework.CurrentCulture = CultureInfo.CurrentUICulture; //Always use en-US NumberFormat because of mySql Requirements GlobalFramework.CurrentCultureNumberFormat = CultureInfo.GetCultureInfo(SettingsApp.CultureNumberFormat); //Init AppSession string appSessionFile = Utils.GetSessionFileName(); if (databaseCreated && File.Exists(appSessionFile)) { File.Delete(appSessionFile); } GlobalFramework.SessionApp = GlobalFrameworkSession.InitSession(appSessionFile); //Try to Get open Session Day/Terminal for this Terminal GlobalFramework.WorkSessionPeriodDay = ProcessWorkSessionPeriod.GetSessionPeriod(WorkSessionPeriodType.Day); GlobalFramework.WorkSessionPeriodTerminal = ProcessWorkSessionPeriod.GetSessionPeriod(WorkSessionPeriodType.Terminal); //Use Detected ScreenSize string appScreenSize = string.IsNullOrEmpty(GlobalFramework.Settings["appScreenSize"]) ? GlobalFramework.PreferenceParameters["APP_SCREEN_SIZE"] : GlobalFramework.Settings["appScreenSize"]; if (appScreenSize.Replace(" ", string.Empty).Equals("0,0") || string.IsNullOrEmpty(appScreenSize)) { // Force Unknown Screen Size //GlobalApp.ScreenSize = new Size(2000, 1800); GlobalApp.ScreenSize = Utils.GetThemeScreenSize(); } //Use config ScreenSize else { Size configAppScreenSize = Utils.StringToSize(appScreenSize); GlobalApp.ScreenSize = Utils.GetThemeScreenSize(configAppScreenSize); } // Init ExpressionEvaluator GlobalApp.ExpressionEvaluator.EvaluateFunction += ExpressionEvaluatorExtended.ExpressionEvaluator_EvaluateFunction; // Init Variables ExpressionEvaluatorExtended.InitVariablesStartupWindow(); ExpressionEvaluatorExtended.InitVariablesPosMainWindow(); // Define Max Dialog Window Size GlobalApp.MaxWindowSize = new Size(GlobalApp.ScreenSize.Width - 40, GlobalApp.ScreenSize.Height - 40); // Add Variables to ExpressionEvaluator.Variables Singleton GlobalApp.ExpressionEvaluator.Variables.Add("globalScreenSize", GlobalApp.ScreenSize); //Parse and store Theme in Singleton try { GlobalApp.Theme = XmlToObjectParser.ParseFromFile(SettingsApp.FileTheme); // Use with dynamic Theme properties like: // GlobalApp.Theme.Theme.Frontoffice.Window[0].Globals.Name = PosBaseWindow // GlobalApp.Theme.Theme.Frontoffice.Window[1].Objects.TablePadUser.Position = 50,50 // or use predicate with from object id ex //var predicate = (Predicate<dynamic>)((dynamic x) => x.ID == "StartupWindow"); //var themeWindow = GlobalApp.Theme.Theme.Frontoffice.Window.Find(predicate); //_log.Debug(string.Format("Message: [{0}]", themeWindow.Globals.Title)); } catch (Exception ex) { Utils.ShowMessageTouchErrorRenderTheme(GlobalApp.WindowStartup, ex.Message); } //Init FastReports Custom Functions and Custom Vars CustomFunctions.Register(SettingsApp.AppName); //Hardware : Init Display if (GlobalFramework.LoggedTerminal.PoleDisplay != null) { GlobalApp.UsbDisplay = (UsbDisplayDevice)UsbDisplayDevice.InitDisplay(); GlobalApp.UsbDisplay.WriteCentered(string.Format("{0} {1}", SettingsApp.AppName, FrameworkUtils.ProductVersion), 1); GlobalApp.UsbDisplay.WriteCentered(SettingsApp.AppUrl, 2); GlobalApp.UsbDisplay.EnableStandBy(); } //Hardware : Init BarCodeReader if (GlobalFramework.LoggedTerminal.BarcodeReader != null) { GlobalApp.BarCodeReader = new InputReader(); } //Hardware : Init WeighingBalance if (GlobalFramework.LoggedTerminal.WeighingMachine != null) { GlobalApp.WeighingBalance = new WeighingBalance(GlobalFramework.LoggedTerminal.WeighingMachine); //_log.Debug(string.Format("IsPortOpen: [{0}]", GlobalApp.WeighingBalance.IsPortOpen())); } //Start Database Backup Timer if not create XPO Schema and SoftwareVendor is Active if (GlobalFramework.PluginSoftwareVendor != null && validDirectoryBackup && !xpoCreateDatabaseAndSchema) { _backupDatabaseTimeSpan = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIMESPAN"]); _databaseBackupTimeSpanRangeStart = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIME_SPAN_RANGE_START"]); _databaseBackupTimeSpanRangeEnd = TimeSpan.Parse(GlobalFramework.PreferenceParameters["DATABASE_BACKUP_TIME_SPAN_RANGE_END"]); StartBackupTimer(); } //Send To Log _log.Debug(string.Format("ProductVersion: [{0}], ImageRuntimeVersion: [{1}], IsLicensed: [{2}]", FrameworkUtils.ProductVersion, FrameworkUtils.ProductAssembly.ImageRuntimeVersion, LicenceManagement.IsLicensed)); //Audit FrameworkUtils.Audit("APP_START", string.Format("{0} {1} clr {2}", SettingsApp.AppName, FrameworkUtils.ProductVersion, FrameworkUtils.ProductAssembly.ImageRuntimeVersion)); if (databaseCreated) { FrameworkUtils.Audit("DATABASE_CREATE"); } // Plugin Errors Messages if (GlobalFramework.PluginSoftwareVendor == null || !GlobalFramework.PluginSoftwareVendor.IsValidSecretKey(SettingsApp.SecretKey)) { Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(650, 380), MessageType.Error, ButtonsType.Ok, Resx.global_error, Resx.dialog_message_error_plugin_softwarevendor_not_registered); _log.Debug(String.Format("Wrong key detected [{0}]. Use a valid LogicposFinantialLibrary with same key as SoftwareVendorPlugin", SettingsApp.SecretKey)); } //Create SystemNotification FrameworkUtils.SystemNotification(); //Clean Documents Folder on New Database, else we have Document files that dont correspond to Database if (databaseCreated && Directory.Exists(GlobalFramework.Path["documents"].ToString())) { string documentsFolder = GlobalFramework.Path["documents"].ToString(); System.IO.DirectoryInfo di = new DirectoryInfo(documentsFolder); if (di.GetFiles().Length > 0) { _log.Debug(string.Format("New database created. Start Delete [{0}] document(s) from [{1}] folder!", di.GetFiles().Length, documentsFolder)); foreach (FileInfo file in di.GetFiles()) { try { file.Delete(); } catch (Exception) { _log.Error(string.Format("Error! Cant delete Document file : [{0}]", file.Name)); } } } } } catch (Exception ex) { _log.Error(ex.Message, ex); } }