Пример #1
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

        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
                        SettingsApp.firstBoot = true;
                        databaseCreated       = DataLayer.CreateDatabaseSchema(xpoConnectionString, GlobalFramework.DatabaseType, GlobalFramework.DatabaseName);
                    }
                    catch (Exception ex)
                    {
                        //Extra protection to prevent goes to login without a valid connection
                        _log.Error("void Init() :: DataLayer.CreateDatabaseSchema :: " + ex.Message, ex);

                        /* IN009034 */
                        GlobalApp.DialogThreadNotify.WakeupMain();

                        Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), ex.Message);
                        Environment.Exit(0);
                    }
                }
                SettingsApp.firstBoot = false;
                //Init XPO Connector DataLayer
                try
                {
                    /* IN007011 */
                    var connectionStringBuilder = new System.Data.Common.DbConnectionStringBuilder()
                    {
                        ConnectionString = xpoConnectionString
                    };
                    if (connectionStringBuilder.ContainsKey("password"))
                    {
                        connectionStringBuilder["password"] = "******";
                    }
                    ;
                    _log.Debug(string.Format("void Init() :: Init XpoDefault.DataLayer: [{0}]", connectionStringBuilder.ToString()));

                    XpoDefault.DataLayer       = XpoDefault.GetDataLayer(xpoConnectionString, xpoAutoCreateOption);
                    GlobalFramework.SessionXpo = new Session(XpoDefault.DataLayer)
                    {
                        LockingOption = LockingOption.None
                    };
                }
                catch (Exception ex)
                {
                    _log.Error("void Init() :: Init XpoDefault.DataLayer: " + ex.Message, ex);

                    /* IN009034 */
                    GlobalApp.DialogThreadNotify.WakeupMain();

                    Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(900, 700), MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), ex.Message);
                    throw; // TO DO
                }

                //Check Valid Database Scheme
                if (!xpoCreateDatabaseAndSchema && !FrameworkUtils.IsRunningOnMono())
                {
                    bool isSchemaValid = DataLayer.IsSchemaValid(xpoConnectionString);
                    _log.Debug(string.Format("void Init() :: Check if Database Scheme: isSchemaValid : [{0}]", isSchemaValid));
                    if (!isSchemaValid)
                    {
                        /* IN009034 */
                        GlobalApp.DialogThreadNotify.WakeupMain();

                        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, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "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)
                {
                    /* IN009034 */
                    GlobalApp.DialogThreadNotify.WakeupMain();

                    string endMessage = "Xpo Create Schema and Fixtures Done!{0}Please assign false to 'xpoCreateDatabaseAndSchema' and 'xpoCreateDatabaseObjectsWithFixtures' and run App again";
                    _log.Debug(string.Format("void Init() :: xpoCreateDatabaseAndSchema: {0}", endMessage));

                    Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(500, 300), MessageType.Info, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_information"), string.Format(endMessage, Environment.NewLine));
                    Environment.Exit(0);
                }

                //Init PreferenceParameters
                GlobalFramework.PreferenceParameters = FrameworkUtils.GetPreferencesParameters();
                //Init Preferences Path
                MainApp.InitPathsPrefs();

                //CultureInfo/Localization
                string culture = GlobalFramework.PreferenceParameters["CULTURE"];

                /* IN008013 */
                if (String.IsNullOrEmpty(culture))
                {
                    culture = GlobalFramework.Settings["customCultureResourceDefinition"];
                }

                //if (!string.IsNullOrEmpty(culture))
                //{
                /* IN006018 and IN007009 */
                //logicpos.shared.App.CustomRegion.RegisterCustomRegion();
                //Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
                //}
                //if (!Utils.IsLinux)
                //{
                //    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
                //}
                GlobalFramework.CurrentCulture = CultureInfo.CurrentUICulture;

                /* IN006018 and IN007009 */
                _log.Debug(string.Format("CUSTOM CULTURE :: CurrentUICulture '{0}' in use.", 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);
                //to used in shared projects
                GlobalFramework.screenSize = 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)
                {
                    /* IN009034 */
                    GlobalApp.DialogThreadNotify.WakeupMain();

                    _log.Debug("void Init() :: XmlToObjectParser.ParseFromFile(SettingsApp.FileTheme) :: " + 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()));
                }

                //Send To Log
                _log.Debug(string.Format("void Init() :: 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))
                {
                    /* IN009034 */
                    GlobalApp.DialogThreadNotify.WakeupMain();

                    _log.Debug(String.Format("void Init() :: Wrong key detected [{0}]. Use a valid LogicposFinantialLibrary with same key as SoftwareVendorPlugin", SettingsApp.SecretKey));
                    Utils.ShowMessageTouch(GlobalApp.WindowStartup, DialogFlags.Modal, new Size(650, 380), MessageType.Error, ButtonsType.Ok, resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "global_error"), resources.CustomResources.GetCustomResources(GlobalFramework.Settings["customCultureResourceDefinition"], "dialog_message_error_plugin_softwarevendor_not_registered"));
                }

                // TK013134: HardCoded Modules : PakingTicket
                try
                {
                    // Override default AppUseParkingTicketModule
                    /* IN009239 */
                    //GlobalFramework.AppUseParkingTicketModule = Convert.ToBoolean(GlobalFramework.Settings["appMultiUserEnvironment"]);
                    CustomAppOperationMode customAppOperationMode = FrameworkUtils.GetCustomAppOperationMode();
                    GlobalFramework.AppUseParkingTicketModule = CustomAppOperationMode.PARKING.Equals(customAppOperationMode);

                    //TK016235 BackOffice - Mode
                    GlobalFramework.AppUseBackOfficeMode = CustomAppOperationMode.BACKOFFICE.Equals(customAppOperationMode);

                    // Init Global Object GlobalApp.ParkingTicket
                    if (GlobalFramework.AppUseParkingTicketModule)
                    {
                        GlobalApp.ParkingTicket = new ParkingTicket();
                    }
                }
                catch (Exception)
                {
                    _log.Error(string.Format("void Init() :: Missing AppUseParkingTicketModule Token in Settings, using default value: [{0}]", GlobalFramework.AppUseParkingTicketModule));
                }

                //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("void Init() :: 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("void Init() :: Error! Cant delete Document file: [{0}]", file.Name));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error("void Init() :: " + ex.Message, ex);
            }
        }