private void button2_Click(object sender, EventArgs e)
 {
     using (var c = new SqlConnection(_builder.ToString()))
     {
         try
         {
             c.Open();
             this.DialogResult = System.Windows.Forms.DialogResult.OK;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
        public bool Connect()
        {
            var builder = new System.Data.Common.DbConnectionStringBuilder();

            builder["Username"] = _view.Username;
            builder["Password"] = _view.Password;
            builder["Service"]  = _view.Service;
            if (!string.IsNullOrEmpty(_view.OracleSchema))
            {
                builder["OracleSchema"] = _view.OracleSchema;
            }
            if (!string.IsNullOrEmpty(_view.KingFdoClass))
            {
                builder["KingFdoClass"] = _view.KingFdoClass;
            }
            if (!string.IsNullOrEmpty(_view.SdeSchema))
            {
                builder["SDE Schema"] = _view.SdeSchema;
            }
            FdoConnection conn = new FdoConnection("OSGeo.KingOracle", builder.ToString());

            if (conn.Open() == FdoConnectionState.Open)
            {
                IFdoConnectionManager mgr = ServiceManager.Instance.GetService <IFdoConnectionManager>();
                mgr.AddConnection(_view.ConnectionName, conn);
                return(true);
            }

            _view.ShowMessage(null, "Connection failed");
            return(false);
        }
Beispiel #3
0
        private string GetPartialConnectionStringForDataStoreEnumeration()
        {
            var builder = new System.Data.Common.DbConnectionStringBuilder();

            builder["Service"]  = _fs.GetConnectionProperty("Service"); //NOXLATE
            builder["Username"] = txtUsername.Text;                     //_fs.GetConnectionProperty("Username"); //NOXLATE
            builder["Password"] = txtPassword.Text;                     //_fs.GetConnectionProperty("Password"); //NOXLATE
            return(builder.ToString());
        }
        private string GetPartialConnectionString()
        {
            var builder = new System.Data.Common.DbConnectionStringBuilder();

            foreach (DataGridViewRow row in grdConnectionParameters.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                {
                    if (!string.IsNullOrEmpty(row.Cells[1].Value.ToString()))
                    {
                        builder[row.Cells[0].Value.ToString()] = row.Cells[1].Value;
                    }
                }
            }
            return(builder.ToString());
        }
Beispiel #5
0
        public void TestConnectionString()
        {
            System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
            builder["Foo"] = "sdfjkg";
            builder["Bar"] = "skgjuksdf";
            builder["Snafu"] = "asjdgjh;sdgj"; //Note the ; in the value
            builder["Whatever"] = "asjd=gjh;sdgj"; //Note the ; and = in the value

            var values = ConnectionProviderRegistry.ParseConnectionString(builder.ToString());
            Assert.AreEqual(values.Count, 4);

            Assert.AreEqual(builder["Foo"].ToString(), values["Foo"]);
            Assert.AreEqual(builder["Bar"].ToString(), values["Bar"]);
            Assert.AreEqual(builder["Snafu"].ToString(), values["Snafu"]);
            Assert.AreEqual(builder["Whatever"].ToString(), values["Whatever"]);
        }
Beispiel #6
0
        public void TestConnectionString()
        {
            System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
            builder["Foo"]      = "sdfjkg";
            builder["Bar"]      = "skgjuksdf";
            builder["Snafu"]    = "asjdgjh;sdgj";  //Note the ; in the value
            builder["Whatever"] = "asjd=gjh;sdgj"; //Note the ; and = in the value

            var values = ConnectionProviderRegistry.ParseConnectionString(builder.ToString());

            Assert.AreEqual(values.Count, 4);

            Assert.AreEqual(builder["Foo"].ToString(), values["Foo"]);
            Assert.AreEqual(builder["Bar"].ToString(), values["Bar"]);
            Assert.AreEqual(builder["Snafu"].ToString(), values["Snafu"]);
            Assert.AreEqual(builder["Whatever"].ToString(), values["Whatever"]);
        }
        public bool Connect()
        {
            var builder = new System.Data.Common.DbConnectionStringBuilder();
            builder["Username"] = _view.Username;
            builder["Password"] = _view.Password;
            builder["Service"] = _view.Service;
            if (!string.IsNullOrEmpty(_view.OracleSchema))
                builder["OracleSchema"] = _view.OracleSchema;
            if (!string.IsNullOrEmpty(_view.KingFdoClass))
                builder["KingFdoClass"] = _view.KingFdoClass;
            if (!string.IsNullOrEmpty(_view.SdeSchema))
                builder["SDE Schema"] = _view.SdeSchema;
            FdoConnection conn = new FdoConnection("OSGeo.KingOracle", builder.ToString());
            if (conn.Open() == FdoConnectionState.Open)
            {
                IFdoConnectionManager mgr = ServiceManager.Instance.GetService<IFdoConnectionManager>();
                mgr.AddConnection(_view.ConnectionName, conn);
                return true;
            }

            _view.ShowMessage(null, "Connection failed");
            return false;
        }
Beispiel #8
0
 private string GetPartialConnectionString()
 {
     var builder = new System.Data.Common.DbConnectionStringBuilder();
     foreach (DataGridViewRow row in grdConnectionParameters.Rows)
     {
         if (row.Cells[0].Value != null && row.Cells[1].Value != null)
         {
             if (!string.IsNullOrEmpty(row.Cells[1].Value.ToString()))
                 builder[row.Cells[0].Value.ToString()] = row.Cells[1].Value;
         }
     }
     return builder.ToString();
 }
        public void Validate(TextWriter stdout)
        {
            var bounds = this.Bounds;

            if (!Utility.InRange(bounds.MinX, -180, 180))
            {
                throw new Exception("minx not in range of [-180, 180]");
            }
            if (!Utility.InRange(bounds.MaxX, -180, 180))
            {
                throw new Exception("maxx not in range of [-180, 180]");
            }
            if (!Utility.InRange(bounds.MinY, -90, 90))
            {
                throw new Exception("miny not in range of [-90, 90]");
            }
            if (!Utility.InRange(bounds.MaxY, -90, 90))
            {
                throw new Exception("maxy not in range of [-90, 90]");
            }

            if (bounds.MinX > bounds.MaxX)
            {
                throw new Exception("Invalid BBOX: minx > maxx");
            }
            if (bounds.MinY > bounds.MaxY)
            {
                throw new Exception("Invalid BBOX: miny > maxy");
            }

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

            builder["Url"]                  = this.MapAgent;                                                                      //NOXLATE
            builder["Username"]             = this.Username;                                                                      //NOXLATE
            builder["Password"]             = this.Password;                                                                      //NOXLATE
            builder["Locale"]               = "en";                                                                               //NOXLATE
            builder["AllowUntestedVersion"] = true;                                                                               //NOXLATE

            string agent = "MapGuide Maestro v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); //NOXLATE

            var conn = ConnectionProviderRegistry.CreateConnection("Maestro.Http", builder.ToString());                           //NOXLATE

            conn.SetCustomProperty("UserAgent", agent);                                                                           //NOXLATE

            // Must be MapGuide Open Source 4.0
            if (conn.SiteVersion < new Version(4, 0))
            {
                throw new Exception($"This tool requires capabilities present in MapGuide Open Source 4.0 and newer. Version {conn.SiteVersion} is not supported");
            }

            if (!string.IsNullOrEmpty(this.ImageTileSetDefinition))
            {
                var resId = new ResourceIdentifier(this.ImageTileSetDefinition);
                if (resId.ResourceType != nameof(ResourceTypes.TileSetDefinition))
                {
                    throw new Exception("Image tile set definiiton is not a tile set definition resource id");
                }

                var tsd = conn.ResourceService.GetResource(this.ImageTileSetDefinition) as ITileSetDefinition;
                if (tsd == null)
                {
                    throw new Exception("Not an image tile set definition resource");
                }

                if (tsd.TileStoreParameters.TileProvider != "XYZ")
                {
                    throw new Exception("Not a XYZ image tile set definition resource");
                }

                if (string.IsNullOrEmpty(this.ImageTileSetGroup))
                {
                    this.ImageTileSet.GroupName = tsd.BaseMapLayerGroups.First().Name;
                    stdout.WriteLine($"Defaulting to layer group ({this.ImageTileSetGroup}) for image tileset");
                }
                else
                {
                    if (!tsd.GroupExists(this.ImageTileSetGroup))
                    {
                        throw new Exception($"The specified group ({this.ImageTileSetGroup}) does not exist in the specified image tile set definition");
                    }
                }
            }
            if (!string.IsNullOrEmpty(this.UTFGridTileSetDefinition))
            {
                var resId = new ResourceIdentifier(this.UTFGridTileSetDefinition);
                if (resId.ResourceType != nameof(ResourceTypes.TileSetDefinition))
                {
                    throw new Exception("UTFGrid tile set definiiton is not a tile set definition resource id");
                }

                var tsd = conn.ResourceService.GetResource(this.UTFGridTileSetDefinition) as ITileSetDefinition;
                if (tsd == null)
                {
                    throw new Exception("Not an UTFGrid tile set definition resource");
                }

                if (tsd.TileStoreParameters.TileProvider != "XYZ")
                {
                    throw new Exception("Not a XYZ UTFGrid tile set definition resource");
                }

                if (string.IsNullOrEmpty(this.UTFGridTileSetGroup))
                {
                    this.UTFGridTileSet.GroupName = tsd.BaseMapLayerGroups.First().Name;
                    stdout.WriteLine($"Defaulting to layer group ({this.UTFGridTileSetGroup}) for utfgrid tileset");
                }
                else
                {
                    if (!tsd.GroupExists(this.UTFGridTileSetGroup))
                    {
                        throw new Exception($"The specified group ({this.UTFGridTileSetGroup}) does not exist in the specified utfgrid tile set definition");
                    }
                }
            }

            Connection = conn;
        }
        public IDbConnection GetDBConnection(SQLMap map)
        {
            if (map.MyMapSign.StartsWith(BTulz.ModelsTransformer.Transformer.SQLs.SQLMapFactory.DEFAULT_DB_TYPE_SIGN))
            {
                var constrBuider = new SqlConnectionStringBuilder();
                constrBuider.DataSource     = this.DBServer;
                constrBuider.UserID         = this.DBUser;
                constrBuider.Password       = this.DBPassword;
                constrBuider.InitialCatalog = this.DBName;
                constrBuider.ConnectTimeout = 600;
                //if (!string.IsNullOrEmpty(map.DefaultDatabase))
                //    constrBuider.InitialCatalog = map.DefaultDatabase;

                return(new SqlConnection(constrBuider.ConnectionString));
            }
            else
            {
                var conBuilder = new System.Data.Common.DbConnectionStringBuilder();
                DbConnectionItem dbNameItem = map.DbConnectionItems.FirstOrDefault(c => c.ItemName == DbConnectionItem.DB_CONNECTION_ITEM_DB_NAME);
                //如果设置了默认数据库,使用默认数据库为打开数据库
                if (!string.IsNullOrEmpty(map.DefaultDatabase))
                {
                    if (dbNameItem != null)
                    {
                        dbNameItem.ItemValue = map.DefaultDatabase;
                    }
                }
                //构建连接字符串项目
                foreach (var dbItem in map.DbConnectionItems)
                {
                    conBuilder.Add(dbItem.StringBuilderKey, dbItem.ItemValue);
                }
                if (!string.IsNullOrEmpty(map.DefaultDatabase))
                {
                    //修正回原始数据库
                    dbNameItem.ItemValue = this.DBName;
                }

                var tmps = map.DbConnetionClassName.Split(';');
                if (tmps.Length != 2)
                {
                    throw new Exception("无效的连接类设置。参考格式[Dbconnection.dll;Dbconnnection]");
                }
                var dllFile   = tmps[0];
                var className = tmps[1];
                foreach (System.Reflection.Assembly itemAbly in System.AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (!string.Equals(dllFile, itemAbly.ManifestModule.ToString(), StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }
                    var dbCon = itemAbly.CreateInstance(className) as System.Data.IDbConnection;
                    if (dbCon != null)
                    {
                        if (map.MyMapSign == "HANA")
                        {
                            dbCon.ConnectionString = string.Format(@"{0};CS=""{1}""", conBuilder.ToString(), dbNameItem.ItemValue);
                        }
                        else if (map.MyMapSign == "MYSQL")
                        {
                            dbCon.ConnectionString = conBuilder.ToString() + ";Allow User Variables = True";
                        }
                        else
                        {
                            dbCon.ConnectionString = conBuilder.ToString();
                        }
                        return(dbCon);
                    }
                }
            }
            throw new Exception("无法获取的数据库连接。");
        }
Beispiel #11
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            using (new WaitCursor(this))
            {
                try
                {
                    PreferedSite ps = null;

                    if (_selectedIndex == 0) //HTTP
                    {
                        var builder = new System.Data.Common.DbConnectionStringBuilder();
                        builder["Url"]                  = _http.Server;                                                                       //NOXLATE
                        builder["Username"]             = _http.Username;                                                                     //NOXLATE
                        builder["Password"]             = _http.Password;                                                                     //NOXLATE
                        builder["Locale"]               = _http.Language;                                                                     //NOXLATE
                        builder["AllowUntestedVersion"] = true;                                                                               //NOXLATE

                        string agent = "MapGuide Maestro v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); //NOXLATE

                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.Http", builder.ToString());                              //NOXLATE
                        _conn.SetCustomProperty("UserAgent", agent);                                                                          //NOXLATE

                        //Update preferred site entry if it exists
                        int index = 0;
                        foreach (PreferedSite s in _http.GetSites())
                        {
                            if (s.SiteURL == _http.Server)
                            {
                                ps = s;
                                break;
                            }
                            else
                            {
                                index++;
                            }
                        }

                        if (ps == null)
                        {
                            ps = new PreferedSite();
                        }

                        if (ps.ApprovedVersion == null)
                        {
                            ps.ApprovedVersion = new Version(0, 0, 0, 0);
                        }

                        if (_conn.SiteVersion > _conn.MaxTestedVersion && _conn.SiteVersion > ps.ApprovedVersion)
                        {
                            if (MessageBox.Show(this, Strings.UntestedServerVersion, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) != DialogResult.Yes)
                            {
                                return;
                            }
                        }

                        try
                        {
                            ps.SiteURL         = _http.Server;
                            ps.StartingPoint   = _http.StartingPoint;
                            ps.Username        = _http.Username;
                            ps.SavePassword    = chkSavePassword.Checked;
                            ps.ApprovedVersion = ps.ApprovedVersion > _conn.SiteVersion ? ps.ApprovedVersion : _conn.SiteVersion;
                            if (ps.SavePassword)
                            {
                                ps.UnscrambledPassword = _http.Password;
                            }
                            else
                            {
                                ps.ScrambledPassword = string.Empty;
                            }

                            if (index >= _siteList.Sites.Length)
                            {
                                _siteList.AddSite(ps);
                            }

                            //_siteList.AutoConnect = chkAutoConnect.Checked;
                            _siteList.PreferedSite = index;
                            var ci = _http.SelectedCulture;
                            if (ci != null)
                            {
                                _siteList.GUILanguage = ci.Name;
                            }
                            _siteList.Save();
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else if (_selectedIndex == 1) //Native
                    {
                        System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
                        builder["ConfigFile"] = LocalNativeLoginCtrl.LastIniPath;                                         //NOXLATE
                        builder["Username"]   = _localNative.Username;                                                    //NOXLATE
                        builder["Password"]   = _localNative.Password;                                                    //NOXLATE
                        builder["Locale"]     = System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName; //NOXLATE
                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.LocalNative", builder.ToString());   //NOXLATE
                    }
                    else //Local
                    {
                        NameValueCollection param = new NameValueCollection();
                        param["ConfigFile"] = LocalLoginCtrl.LastIniPath;                            //NOXLATE
                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.Local", param); //NOXLATE
                    }

                    _conn.AutoRestartSession = true;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (TargetInvocationException ex)
                {
                    //We don't care about the outer exception
                    string msg = ex.InnerException.Message;
                    if (msg.IndexOf("MgConnectionFailedException") >= 0)
                    {
                        new ConnectionErrorDialog().ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show(this, string.Format(Strings.ConnectionFailedError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    if (msg.IndexOf("MgConnectionFailedException") >= 0)
                    {
                        new ConnectionErrorDialog().ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show(this, string.Format(Strings.ConnectionFailedError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Beispiel #12
0
 private string GetPartialConnectionStringForDataStoreEnumeration()
 {
     var builder = new System.Data.Common.DbConnectionStringBuilder();
     builder["Service"] = _fs.GetConnectionProperty("Service"); //NOXLATE
     builder["Username"] = txtUsername.Text; //_fs.GetConnectionProperty("Username"); //NOXLATE
     builder["Password"] = txtPassword.Text; //_fs.GetConnectionProperty("Password"); //NOXLATE
     return builder.ToString();
 }
Beispiel #13
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);
            }
        }
Beispiel #14
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            using (new WaitCursor(this))
            {
                try
                {
                    PreferedSite ps = null;

                    if (_selectedIndex == 0) //HTTP
                    {
                        var builder = new System.Data.Common.DbConnectionStringBuilder();
                        builder["Url"] = _http.Server; //NOXLATE
                        builder["Username"] = _http.Username; //NOXLATE
                        builder["Password"] = _http.Password; //NOXLATE
                        builder["Locale"] = _http.Language; //NOXLATE
                        builder["AllowUntestedVersion"] = true; //NOXLATE

                        string agent = "MapGuide Maestro v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); //NOXLATE

                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.Http", builder.ToString()); //NOXLATE
                        _conn.SetCustomProperty("UserAgent", agent); //NOXLATE

                        //Update preferred site entry if it exists
                        int index = 0;
                        foreach (PreferedSite s in _http.GetSites())
                        {
                            if (s.SiteURL == _http.Server)
                            {
                                ps = s;
                                break;
                            }
                            else
                                index++;
                        }

                        if (ps == null)
                            ps = new PreferedSite();

                        if (ps.ApprovedVersion == null)
                            ps.ApprovedVersion = new Version(0, 0, 0, 0);

                        if (_conn.SiteVersion > _conn.MaxTestedVersion && _conn.SiteVersion > ps.ApprovedVersion)
                        {
                            if (MessageBox.Show(this, Strings.UntestedServerVersion, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) != DialogResult.Yes)
                                return;
                        }

                        try
                        {
                            ps.SiteURL = _http.Server;
                            ps.StartingPoint = _http.StartingPoint;
                            ps.Username = _http.Username;
                            ps.SavePassword = chkSavePassword.Checked;
                            ps.ApprovedVersion = ps.ApprovedVersion > _conn.SiteVersion ? ps.ApprovedVersion : _conn.SiteVersion;
                            if (ps.SavePassword)
                                ps.UnscrambledPassword = _http.Password;
                            else
                                ps.ScrambledPassword = string.Empty;

                            if (index >= _siteList.Sites.Length)
                                _siteList.AddSite(ps);

                            //_siteList.AutoConnect = chkAutoConnect.Checked;
                            _siteList.PreferedSite = index;
                            var ci = _http.SelectedCulture;
                            if (ci != null)
                            {
                                _siteList.GUILanguage = ci.Name;
                            }
                            _siteList.Save();
                        }
                        catch (Exception)
                        {

                        }
                    }
                    else if (_selectedIndex == 1) //Native
                    {
                        System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
                        builder["ConfigFile"] = LocalNativeLoginCtrl.LastIniPath; //NOXLATE
                        builder["Username"] = _localNative.Username; //NOXLATE
                        builder["Password"] = _localNative.Password; //NOXLATE
                        builder["Locale"] = System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName; //NOXLATE
                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.LocalNative", builder.ToString()); //NOXLATE
                    }
                    else //Local
                    {
                        NameValueCollection param = new NameValueCollection();
                        param["ConfigFile"] = LocalLoginCtrl.LastIniPath; //NOXLATE
                        _conn = ConnectionProviderRegistry.CreateConnection("Maestro.Local", param); //NOXLATE
                    }

                    _conn.AutoRestartSession = true;

                    this.DialogResult = DialogResult.OK;
                    this.Close();

                }
                catch (TargetInvocationException ex)
                {
                    //We don't care about the outer exception
                    string msg = ex.InnerException.Message;
                    MessageBox.Show(this, string.Format(Strings.ConnectionFailedError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    MessageBox.Show(this, string.Format(Strings.ConnectionFailedError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }