Beispiel #1
0
        private void ReadConfigurationFile()
        {
            _connectionString = ConfigurationManager.ConnectionStrings["Dynamics365ConnectionString"]?.ConnectionString;

            var connStringBuilder = new System.Data.Common.DbConnectionStringBuilder();

            connStringBuilder.ConnectionString = _connectionString;

            _dynamics365Url = connStringBuilder.ContainsKey("Url") ? connStringBuilder["Url"].ToString() : string.Empty;
            _username       = connStringBuilder.ContainsKey("Username") ? connStringBuilder["Username"].ToString() : string.Empty;
            _password       = connStringBuilder.ContainsKey("Password") ? connStringBuilder["Password"].ToString() : string.Empty;
        }
Beispiel #2
0
        public bool DatabaseExists()
        {
            const string strSql = "SELECT DB_ID(@Database) ";
            bool         result = false;

            System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder
            {
                ConnectionString = SqlHelper.ConnString
            };
            if (!builder.ContainsKey("initial catalog"))
            {
                return(true);
            }

            string database = builder["initial catalog"] as string;

            builder["initial catalog"] = "master";

            var res = SqlHelper.ExecuteScalar(builder.ConnectionString, CommandType.Text, strSql, new SqlParameter("@Database", SqlDbType.VarChar)
            {
                Value = database
            });

            result = (res.ConvertDBNull() != DBNull.Value);

            return(result);
        }
        string normalizeConnectionString(string s)
        {
            var builder = new System.Data.Common.DbConnectionStringBuilder();

            try
            {
                builder.ConnectionString = s.Trim();
                if (builder.ContainsKey("provider connection string"))
                {
                    s = (string)builder["provider connection string"];
                }
            }
            catch (ArgumentException) {}

            return(s);
        }
Beispiel #4
0
        public bool DatabaseExists()
        {
            const string strSql = "SELECT DB_ID(@Database) ";
            bool result = false;
            System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder
                                                                   {
                                                                       ConnectionString = SqlHelper.ConnString
                                                                   };
            if (!builder.ContainsKey("initial catalog"))
                return true;

            string database = builder["initial catalog"] as string;
            builder["initial catalog"] = "master";

            var res = SqlHelper.ExecuteScalar(builder.ConnectionString, CommandType.Text, strSql, new SqlParameter("@Database", SqlDbType.VarChar) { Value = database });

            result = (res.ConvertDBNull() != DBNull.Value);

            return result;
        }
Beispiel #5
0
        /// <summary>
        /// This method determines a provider from the given Connection String.
        /// The default value is the SqlServer provider.
        /// </summary>
        /// <param name="ConnectString">Connection Stirng</param>
        /// <returns>Provider</returns>
        public static EnumProviders GetProvider(string ConnectString)
        {
            EnumProviders provider;

            System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
            builder.ConnectionString = ConnectString;

            // Initial value
            provider = EnumProviders.SqlServer;

            string connectionStringProviderValue = "";
            if (builder.ContainsKey("Provider"))
            { connectionStringProviderValue = builder["Provider"].ToString(); }
            else
            { connectionStringProviderValue = ""; }

            switch (connectionStringProviderValue)
            {
                case "Microsoft.ACE.OLEDB.12.0":
                    provider = EnumProviders.OleDb;
                    break;
                case "Microsoft.Jet.OLEDB.4.0;":
                    provider = EnumProviders.OleDb;
                    break;
                case "SQLNCLI10":
                    provider = EnumProviders.SqlServer;
                    break;
                default:
                    provider = EnumProviders.SqlServer;
                    break;
            }

            return provider;
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureTableStorageErrorLog"/> class
        /// using a dictionary of configured settings.
        /// </summary>

        public AzureTableStorageErrorLog(IDictionary config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            #region Read properties of ErrorLog config item

            //
            // Set the application name as this implementation provides
            // per-application isolation over a single store.
            //

            var appName = config.Find("applicationName", string.Empty);

            //
            // Set the table name. This implementation provides
            // table-per-application-config isolation over a single store.
            //

            var tableName = config.Find("tableName", string.Empty);

            #endregion Read properties of ErrorLog config item

            #region Read properties of ErrorLog connection string

            var cfgBuilder = new System.Data.Common.DbConnectionStringBuilder();
            var originalConnectionString = ElmahHelper.GetConnectionString(config);
            cfgBuilder.ConnectionString = originalConnectionString;

            // Try to override ApplicationName from connection string
            if (cfgBuilder.ContainsKey("ApplicationName"))
            {
                appName = (string)cfgBuilder["ApplicationName"];
                cfgBuilder.Remove("ApplicationName");
            }

            // Try to override TableName from connection string
            if (cfgBuilder.ContainsKey("TableName"))
            {
                tableName = (string)cfgBuilder["TableName"];
                cfgBuilder.Remove("TableName");
            }

            #endregion Read properties of ErrorLog connection string

            if (appName.Length > MaxAppNameLength)
            {
                throw new ApplicationException(string.Format(
                                                   "Application name is too long. Maximum length allowed is {0} characters.",
                                                   MaxAppNameLength.ToString("N0")));
            }

            if (tableName.Length > MaxTableNameLength)
            {
                throw new ApplicationException(string.Format(
                                                   "Table name is too long. Maximum length allowed is {0} characters.",
                                                   MaxTableNameLength.ToString("N0")));
            }

            if (!string.IsNullOrWhiteSpace(appName))
            {
                ApplicationName = appName;
            }

            if (!string.IsNullOrWhiteSpace(tableName))
            {
                TableName = tableName;
            }

            var newConnectionString        = string.Join(";", originalConnectionString.Split(';').Where(item => !item.StartsWith("ApplicationName=", StringComparison.OrdinalIgnoreCase) && !item.StartsWith("TableName=", StringComparison.OrdinalIgnoreCase)));
            var newConnectionStringBuilder = new System.Data.Common.DbConnectionStringBuilder();
            newConnectionStringBuilder.ConnectionString = newConnectionString;

            if (!cfgBuilder.EquivalentTo(newConnectionStringBuilder))
            {
                throw new ApplicationException("Connection string contains invalid parameters.");
            }

            //
            // If there is no connection string to use then throw an
            // exception to abort construction.
            //

            if (cfgBuilder.ConnectionString.Length == 0)
            {
                throw new ApplicationException("Connection string is missing for the Azure Table Storage error log.");
            }

            var cloudStorageAccount = CloudStorageAccount.Parse(newConnectionString);
            var tableClient         = cloudStorageAccount.CreateCloudTableClient();
            _cloudTable = tableClient.GetTableReference(TableName);
            _cloudTable.CreateIfNotExists();
        }
    public override CartoDatasource ToDatasource(ParameterCollection parameters)
    {
      CartoDatasource ds = new CartoDatasource();

      if (parameters != null)
      {
        string type = parameters.GetValue("Type");
        string paramValue = null;

        switch (type.ToLower())
        {
          case "shape":
            if (parameters.TryGetValue("File", out paramValue))
            {
              if (paramValue.EndsWith(".shp"))
                ds.Add("type", type.ToLower());
            }
            else
              throw new Exception("'File' parameter is required.");

            ds.Add("file", paramValue);
            if (parameters.TryGetValue("FileBasedIndex", out paramValue))
              ds.Add("indexed", paramValue.ToLower());
            if (parameters.TryGetValue("Encoding", out paramValue))
              ds.Add("encoding", paramValue.ToLower());
            break;
          case "geojson":
            // ds.Add("type", type.ToLower());
            if (parameters.TryGetValue("File", out paramValue))
              ds.Add("file", paramValue);
            else
              throw new Exception("'File' parameter is required.");

            if (parameters.TryGetValue("FileBasedIndex", out paramValue))
              ds.Add("indexed", paramValue.ToLower());
            if (parameters.TryGetValue("Encoding", out paramValue) && !string.Equals(paramValue, "UTF-8", StringComparison.OrdinalIgnoreCase))
              ds.Add("encoding", paramValue.ToLower());
            break;
          case "ogr":
            ds.Add("type", type.ToLower());
            if (parameters.TryGetValue("File", out paramValue))
              ds.Add("file", paramValue);
            else
              throw new Exception("'File' parameter is required.");

            if (ds.TryGetValue("LayerName", out paramValue))
              ds.Add("layer", paramValue);
            break;
          case "postgis":
            ds.Add("type", type.ToLower());

            if (parameters.TryGetValue("Connection", out paramValue) && !string.IsNullOrEmpty(paramValue))
            {
              System.Data.Common.DbConnectionStringBuilder connParams = new System.Data.Common.DbConnectionStringBuilder();
              connParams.ConnectionString = paramValue;
              if (connParams.ContainsKey("Host") && !string.Equals(connParams["Host"], "localhost"))
                ds.Add("host", connParams["Host"]);
              if (connParams.ContainsKey("Port") && !string.Equals(connParams["Port"], "5432"))
                ds.Add("port", connParams["Port"]);
              if (connParams.ContainsKey("Database"))
                ds.Add("dbname", connParams["Database"]);

              if (connParams.ContainsKey("User ID") && !string.IsNullOrEmpty((string)connParams["User ID"]))
                ds.Add("user", connParams["User ID"]);

              if (connParams.ContainsKey("Password") && !string.IsNullOrEmpty((string)connParams["Password"]))
                ds.Add("password", connParams["Password"]);
            }

            if (parameters.TryGetValue("Extent", out paramValue))
              ds.Add("extent", paramValue);

            if (parameters.TryGetValue("Table_Origin", out paramValue))
              ds.Add("table", paramValue);
            if (parameters.TryGetValue("Query", out paramValue))
              ds.Add("table", paramValue);
            else if (parameters.TryGetValue("Table", out paramValue))
              ds.Add("table", paramValue);


            if (parameters.TryGetValue("GeometryField", out paramValue))
              ds.Add("geometry_field", paramValue);
            break;
          case "mssqlspatial":
            ds.Add("type", type.ToLower());

            if (parameters.TryGetValue("Connection", out paramValue))
              ds.Add("connection", paramValue);
            if (parameters.TryGetValue("GeometryField", out paramValue))
              ds.Add("geometry_field", paramValue);
            if (parameters.TryGetValue("Table", out paramValue))
              ds.Add("table", paramValue);
            if (parameters.TryGetValue("Query", out paramValue) && !string.IsNullOrEmpty(paramValue))
              ds.Add("query", paramValue);
            if (parameters.TryGetValue("SpatialIndex", out paramValue) && !string.IsNullOrEmpty(paramValue))
              ds.Add("spatial_index", paramValue);
            if (parameters.TryGetValue("Extent", out paramValue))
              ds.Add("extent", paramValue);
            break;
          case "spatialite":
            ds.Add("type", type.ToLower());

            if (parameters.TryGetValue("Connection", out paramValue))
              ds.Add("connection", paramValue);
            if (parameters.TryGetValue("GeometryField", out paramValue))
              ds.Add("geometry_field", paramValue);
            if (parameters.TryGetValue("Table", out paramValue))
              ds.Add("table", paramValue);
            if (parameters.TryGetValue("Query", out paramValue))
              ds.Add("query", paramValue);
            if (parameters.TryGetValue("Extent", out paramValue))
              ds.Add("extent", paramValue);
            break;
          case "dem":
            ds.Add("type", type.ToLower());

            if (parameters.TryGetValue("Path", out paramValue))
              ds.Add("path", paramValue);
            if (parameters.TryGetValue("DataSourceType", out paramValue))
              ds.Add("datasource_type", paramValue);
            if (parameters.TryGetValue("CacheSize", out paramValue))
              ds.Add("cache_size", paramValue);
            if (parameters.TryGetValue("FileExtension", out paramValue))
              ds.Add("file_extension", paramValue);
            if (parameters.TryGetValue("DataType", out paramValue))
              ds.Add("data_type", paramValue);
            if (parameters.TryGetValue("IsolineInterval", out paramValue))
              ds.Add("isoline_interval", paramValue);
            if (parameters.TryGetValue("MinElevation", out paramValue))
              ds.Add("min_elevation", paramValue);
            if (parameters.TryGetValue("MaxElevation", out paramValue))
              ds.Add("max_elevation", paramValue);
            if (parameters.TryGetValue("RestoreData", out paramValue))
              ds.Add("restore_data", paramValue);
            if (parameters.TryGetValue("ResampleAlgorithm", out paramValue))
              ds.Add("resampling_algorithm", paramValue);
            if (parameters.TryGetValue("AutoResolution", out paramValue))
              ds.Add("auto_resolution", paramValue);
            if (parameters.TryGetValue("DownsampleResolution", out paramValue))
              ds.Add("downsample_resolution", paramValue);
            if (parameters.TryGetValue("CacheID", out paramValue))
              ds.Add("cache_id", paramValue);
            break;
          case "osm":
            ds.Add("type", type.ToLower());
            if (parameters.TryGetValue("File", out paramValue))
              ds.Add("file", paramValue);
            else
              throw new Exception("'File' parameter is required.");

            if (parameters.TryGetValue("Query", out paramValue))
              ds.Add("query", paramValue);
            if (parameters.TryGetValue("TagsFilter", out paramValue))
              ds.Add("tags_filter", paramValue);
            if (parameters.TryGetValue("BuildSpatialIndex", out paramValue) && !string.IsNullOrEmpty(paramValue))
              ds.Add("spatial_index", paramValue.ToLower());
            if (parameters.TryGetValue("FileBasedIndex", out paramValue) && !string.IsNullOrEmpty(paramValue))
              ds.Add("spatial_index_file", paramValue.ToLower());
            break;
          case "esrifilegeodb":
            ds.Add("type", type.ToLower());

            if (parameters.TryGetValue("Path", out paramValue))
              ds.Add("path", paramValue);
            if (parameters.TryGetValue("Table", out paramValue))
              ds.Add("table", paramValue);
            if (parameters.TryGetValue("Query", out paramValue))
              ds.Add("query", paramValue);
            break;
        }
      }

      return ds;
    }
Beispiel #8
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);
            }
        }
        /// <summary>
        /// Initialize the Connection Parameters using the Connection String Settings
        /// </summary>
        /// <param name="settings"></param>
        public void ReadConnectionParameters(ConnectionStringSettings settings)
        {
            var connectionString = new System.Data.Common.DbConnectionStringBuilder { ConnectionString = settings.ConnectionString };

            if (connectionString.ContainsKey("DriverClass"))
            {
                Connection_DriverClass = (string)connectionString["DriverClass"];
                connectionString.Remove("DriverClass");
            }
            else
                throw new ConnectionElementNotFoundException("DriverClass");

            if (connectionString.ContainsKey("Dialect"))
            {
                Dialect = (string)connectionString["Dialect"];
                connectionString.Remove("Dialect");
            }
            else
                throw new ConnectionElementNotFoundException("Dialect");

            if (connectionString.ContainsKey("TablePrefix"))
            {
                TablePrefix = (string)connectionString["TablePrefix"];
                connectionString.Remove("TablePrefix");
            }

            Connection_ConnectionString = connectionString.ConnectionString;
        }