Ejemplo n.º 1
0
        //执行 sql 语句字符串,0 表示 执行成功
        public static bool ExecuteSql(string strSql)
        {
            if (strSql == null || strSql.Length == 0)
            {
                return(true);
            }

            bool nRet = false;

            using (MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(string.Format(connstring, IP, User, Pass)))
            {
                try
                {
                    conn.Open();
                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(conn, strSql);
                    int ret = script.Execute();
                    conn.Close();
                    nRet = true;
                }
                catch (Exception ex)
                {
                    MyLog4Net.Container.Instance.Log.DebugWithDebugView("ExecuteSql ret err:" + ex);
                    nRet = false;
                }
            }
            return(nRet);
        }
Ejemplo n.º 2
0
        private static void PatchDatabase(string dbType, string host, uint port, string username, string password, string database)
        {
            var updatesPath    = $"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}{dbType}";
            var updatesFile    = $"{updatesPath}{Path.DirectorySeparatorChar}applied_updates.txt";
            var appliedUpdates = Array.Empty <string>();

            var containerUpdatesFile = $"/ace/Config/{dbType}_applied_updates.txt";

            if (IsRunningInContainer && File.Exists(containerUpdatesFile))
            {
                File.Copy(containerUpdatesFile, updatesFile, true);
            }

            if (File.Exists(updatesFile))
            {
                appliedUpdates = File.ReadAllLines(updatesFile);
            }

            Console.WriteLine($"Searching for {dbType} update SQL scripts .... ");
            foreach (var file in new DirectoryInfo(updatesPath).GetFiles("*.sql").OrderBy(f => f.Name))
            {
                if (appliedUpdates.Contains(file.Name))
                {
                    continue;
                }

                Console.Write($"Found {file.Name} .... ");
                var sqlDBFile  = File.ReadAllText(file.FullName);
                var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={host};port={port};user={username};password={password};database={database};DefaultCommandTimeout=120");
                var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                Console.Write($"Importing into {database} database on SQL server at {host}:{port} .... ");
                try
                {
                    script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                    var count = script.Execute();
                    //Console.Write($" {count} database records affected ....");
                    Console.WriteLine(" complete!");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    Console.WriteLine($" error!");
                    Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                }
                File.AppendAllText(updatesFile, file.Name + Environment.NewLine);
            }

            if (IsRunningInContainer && File.Exists(containerUpdatesFile))
            {
                File.Copy(updatesFile, containerUpdatesFile, true);
            }

            Console.WriteLine($"{dbType} update SQL scripts import complete!");
        }
Ejemplo n.º 3
0
        private static void AutoApplyWorldCustomizations()
        {
            var content_folders_search_option = ConfigManager.Config.Offline.RecurseWorldCustomizationPaths ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var content_folders = new List <string> {
                GetContentFolder()
            };

            content_folders.AddRange(ConfigManager.Config.Offline.WorldCustomizationAddedPaths);
            content_folders.Sort();

            Console.WriteLine($"Searching for World Customization SQL scripts .... ");

            content_folders.ForEach(path =>
            {
                var contentDI = new DirectoryInfo(path);
                if (contentDI.Exists)
                {
                    Console.Write($"Searching for SQL files within {path} .... ");

                    foreach (var file in contentDI.GetFiles("*.sql", content_folders_search_option).OrderBy(f => f.FullName))
                    {
                        Console.Write($"Found {file.FullName} .... ");
                        var sqlDBFile  = File.ReadAllText(file.FullName);
                        var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};password={ConfigManager.Config.MySql.World.Password};database={ConfigManager.Config.MySql.World.Database};DefaultCommandTimeout=120");
                        sqlDBFile      = sqlDBFile.Replace("ace_world", ConfigManager.Config.MySql.World.Database);
                        var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                        Console.Write($"Importing into World database on SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} .... ");
                        try
                        {
                            script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                            var count = script.Execute();
                            //Console.Write($" {count} database records affected ....");
                            Console.WriteLine(" complete!");
                        }
                        catch (MySql.Data.MySqlClient.MySqlException ex)
                        {
                            Console.WriteLine($" error!");
                            Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                        }
                    }
                }
            });

            Console.WriteLine($"World Customization SQL scripts import complete!");
        }
        public bool InstallPlugin(string PluginPackagePath, ref string ErrorText)
        {
            string exePath = Path.GetDirectoryName(Application.ExecutablePath);
            if (Directory.Exists(exePath + "/tempDir/"))
            {
                Directory.Delete(exePath + "/tempDir/", true);
            }

            PluginDescription desc = new PluginDescription();
            string tempfolder = exePath + "/tempDir/";
            string zipFileName = Path.GetFullPath(PluginPackagePath);
            string DescPath = null;

            bool NoError = true;

            ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            try
            {
                fastZip.ExtractZip(zipFileName, tempfolder, null);
                // find all included plugin descriptions and install the plugins
                List<string> osapdFiles = new List<string>();
                List<string> sqlFiles = new List<string>();

                string[] pluginFile = Directory.GetFiles(tempfolder, "*.osapd", SearchOption.TopDirectoryOnly);
                osapdFiles.AddRange(pluginFile);
                string[] sqlFile = Directory.GetFiles(tempfolder, "*.sql", SearchOption.TopDirectoryOnly);
                sqlFiles.AddRange(sqlFile);

                if (osapdFiles.Count == 0)
                {
                    MessageBox.Show("No plugin description files found.");
                    return false;
                }

                if (osapdFiles.Count > 1)
                {
                    MessageBox.Show("More than one plugin description file found.");
                    return false;
                }
                if (osapdFiles.Count == 1)
                {

                    DescPath = osapdFiles[0];
                }

                if (!string.IsNullOrEmpty(DescPath))
                {
                    desc.Deserialize(DescPath);

                    //NoError = desc.VerifyInstall(ref ErrorText);

                    //uninstall previous plugin and delete the folder
                    if (UninstallPlugin(desc))
                    {

                        // get the plugin folder path
                        string pluginFolder = desc.Path;
                        if (!string.IsNullOrEmpty(pluginFolder))  //only extract valid plugins
                        {
                            string[] files = System.IO.Directory.GetFiles(tempfolder);

                            string ConnectionString = string.Format("Uid={0};Pwd={1};Server={2};Port={3};Database={4};allow user variables=true",
                                Common.DBUsername, Common.DBPassword, Common.DBConnection, Common.DBPort, Common.DBName);
                            MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
                            connection.Open();
                            foreach (string s in sqlFile)
                            {
                                try
                                {

                                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection, File.ReadAllText(s));
                                    script.Execute();
                                }
                                catch (Exception ex)
                                {
                                    this.Log.Error("Error running sql script: " + s, ex);
                                }
                            }

                            System.IO.Directory.Move(tempfolder, exePath + "/Plugins/" + pluginFolder);

                            //Check if we are running a x64 bit architecture (This is a silly way to do it since I am not sure if every 64 bit machine has this directory...)
                            bool is64bit = Environment.Is64BitOperatingSystem;

                            //Do a check for any x64 assemblies, and prompt the user to install them if they are running a 64 bit machine
                            if (is64bit && (desc.x64Assemblies.Count > 0))
                            {
                                /* x64 assemblies generally have the same name as their x32 counterparts when referenced by the OSA app
                                 * however they are packaged as "filename.ext.x64" so we will replace the 32bit file which is installed by
                                 * default with the 64bit versioin with the same filename.ext
                                 */

                                if (MessageBox.Show(
                                    "You are running an x64 architecture and this plugin has specific assemblies built for 64bit machines." +
                                    " It is highly recommended that you install the 64bit versions to ensure proper compatibility",
                                    "Install 64bit Assemblies?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    //Install the 64bit assemblies over the 32 bit ones...
                                    string[] x64files = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");

                                    foreach (string str in x64files)
                                    {
                                        string destFile = System.IO.Path.Combine(exePath + "/Plugins/" + pluginFolder + "/", System.IO.Path.GetFileNameWithoutExtension(str));
                                        //Copy it to the new destination overwriting the old file if it exists
                                        System.IO.File.Copy(str, destFile, true);
                                    }
                                }
                            }

                            //Delete all the files with .x64 extensions since they aren't needed anymore
                            string[] delfiles = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");
                            foreach (string str in delfiles)
                                System.IO.File.Delete(str);

                            this.Log.Info("Sending message to service to load plugin.");

                        }
                    }
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("catch: " + ex.Message);
                return false;
            }
                if (Directory.Exists(exePath + "/tempDir/"))
                {
                    deleteFolder(exePath + "/tempDir/");
                }

                OSAEMethodManager.MethodQueueAdd("SERVICE-" + Common.ComputerName, "RELOAD PLUGINS", "", "", "Plugin Installer");
            return NoError;
        }
Ejemplo n.º 5
0
        private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation     = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile     = new FileInfo(configJsExample);

            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config   = JsonConvert.DeserializeObject <MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();

            if (IsRunningInContainer)
            {
                variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            }
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.Server.WorldName = variable.Trim();
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.Server.Network.Host = variable.Trim();
            }
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            }
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                {
                    path += Path.DirectorySeparatorChar;
                }
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and password for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The password must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            }
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.MySql.Authentication.Database = variable.Trim();
            }
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            }
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.MySql.Shard.Database = variable.Trim();
            }
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            }
            if (!string.IsNullOrWhiteSpace(variable))
            {
                config.MySql.World.Database = variable.Trim();
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = "n";
            }
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host          = variable.Trim();
                    config.MySql.World.Host          = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port          = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port          = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Shard.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = "y";
            }
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username          = variable.Trim();
                    config.MySql.World.Username          = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the password for your SQL server (default: \"{config.MySql.World.Password}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer)
                {
                    variable = Environment.GetEnvironmentVariable("MYSQL_PASSWORD");
                }
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Password = variable.Trim();
                    config.MySql.Shard.Password          = variable.Trim();
                    config.MySql.World.Password          = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the password for your authentication database (default: \"{config.MySql.Authentication.Password}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Password = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Shard.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the password for your shard database (default: \"{config.MySql.Shard.Password}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Shard.Password = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the password for your world database (default: \"{config.MySql.World.Password}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.World.Password = variable.Trim();
                }
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            }
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ;)
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};password={config.MySql.World.Password}"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile      = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};password={config.MySql.World.Password}";
                    var sqlConnect     = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script         = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql"))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile      = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};password={config.MySql.World.Password}";
                    switch (file.Name)
                    {
                    case "AuthenticationBase":
                        sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};password={config.MySql.Authentication.Password}";
                        break;

                    case "ShardBase":
                        sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};password={config.MySql.Shard.Password}";
                        break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                Console.WriteLine("Searching for Authentication update SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}Authentication").GetFiles("*.sql"))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile  = File.ReadAllText(file.FullName);
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};password={config.MySql.Authentication.Password};database={config.MySql.Authentication.Database}");
                    var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into {config.MySql.Authentication.Database} database on SQL server at {config.MySql.Authentication.Host}:{config.MySql.Authentication.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Authentication update SQL scripts import complete!");

                Console.WriteLine("Searching for Shard update SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}Shard").GetFiles("*.sql"))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile  = File.ReadAllText(file.FullName);
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};password={config.MySql.Shard.Password};database={config.MySql.Shard.Database}");
                    var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into {config.MySql.Shard.Database} database on SQL server at {config.MySql.Shard.Host}:{config.MySql.Shard.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Shard update SQL scripts import complete!");

                Console.WriteLine("Searching for World update SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}World").GetFiles("*.sql"))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile  = File.ReadAllText(file.FullName);
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};password={config.MySql.World.Password};database={config.MySql.World.Database}");
                    var script     = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into {config.MySql.World.Database} database on SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("World update SQL scripts import complete!");
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer)
            {
                variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            }
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url     = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader   = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html     = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json       = JsonConvert.DeserializeObject(html);
                string  tag        = json[0].tag_name;
                string  dbURL      = json[0].assets[0].browser_download_url;
                string  dbFileName = json[0].assets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};password={config.MySql.World.Password}");

                    var line            = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {
                            }
                            completeSQLline = string.Empty;
                        }
                        else
                        {
                            completeSQLline += line + Environment.NewLine;
                        }
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }
Ejemplo n.º 6
0
        public bool InstallPlugin(string PluginPackagePath, ref string ErrorText)
        {
            string exePath = Path.GetDirectoryName(Application.ExecutablePath);

            if (Directory.Exists(exePath + "/tempDir/"))
            {
                Directory.Delete(exePath + "/tempDir/", true);
            }

            PluginDescription desc        = new PluginDescription();
            string            tempfolder  = exePath + "/tempDir/";
            string            zipFileName = Path.GetFullPath(PluginPackagePath);
            string            DescPath    = null;

            bool NoError = true;

            ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            try
            {
                fastZip.ExtractZip(zipFileName, tempfolder, null);
                // find all included plugin descriptions and install the plugins
                List <string> osapdFiles = new List <string>();
                List <string> sqlFiles   = new List <string>();

                string[] pluginFile = Directory.GetFiles(tempfolder, "*.osapd", SearchOption.TopDirectoryOnly);
                osapdFiles.AddRange(pluginFile);
                string[] sqlFile = Directory.GetFiles(tempfolder, "*.sql", SearchOption.TopDirectoryOnly);
                sqlFiles.AddRange(sqlFile);

                if (osapdFiles.Count == 0)
                {
                    MessageBox.Show("No plugin description files found.");
                    return(false);
                }

                if (osapdFiles.Count > 1)
                {
                    MessageBox.Show("More than one plugin description file found.");
                    return(false);
                }
                if (osapdFiles.Count == 1)
                {
                    DescPath = osapdFiles[0];
                }


                if (!string.IsNullOrEmpty(DescPath))
                {
                    desc.Deserialize(DescPath);

                    //NoError = desc.VerifyInstall(ref ErrorText);

                    //uninstall previous plugin and delete the folder
                    if (UninstallPlugin(desc))
                    {
                        // get the plugin folder path
                        string pluginFolder = desc.Path;
                        if (!string.IsNullOrEmpty(pluginFolder))  //only extract valid plugins
                        {
                            string[] files = System.IO.Directory.GetFiles(tempfolder);

                            string ConnectionString = string.Format("Uid={0};Pwd={1};Server={2};Port={3};Database={4};allow user variables=true",
                                                                    Common.DBUsername, Common.DBPassword, Common.DBConnection, Common.DBPort, Common.DBName);
                            MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
                            connection.Open();
                            foreach (string s in sqlFile)
                            {
                                try
                                {
                                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection, File.ReadAllText(s));
                                    script.Execute();
                                }
                                catch (Exception ex)
                                {
                                    this.Log.Error("Error running sql script: " + s, ex);
                                }
                            }

                            System.IO.Directory.Move(tempfolder, exePath + "/Plugins/" + pluginFolder);

                            //Check if we are running a x64 bit architecture (This is a silly way to do it since I am not sure if every 64 bit machine has this directory...)
                            bool is64bit = Environment.Is64BitOperatingSystem;

                            //Do a check for any x64 assemblies, and prompt the user to install them if they are running a 64 bit machine
                            if (is64bit && (desc.x64Assemblies.Count > 0))
                            {
                                /* x64 assemblies generally have the same name as their x32 counterparts when referenced by the OSA app
                                 * however they are packaged as "filename.ext.x64" so we will replace the 32bit file which is installed by
                                 * default with the 64bit versioin with the same filename.ext
                                 */

                                if (MessageBox.Show(
                                        "You are running an x64 architecture and this plugin has specific assemblies built for 64bit machines." +
                                        " It is highly recommended that you install the 64bit versions to ensure proper compatibility",
                                        "Install 64bit Assemblies?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    //Install the 64bit assemblies over the 32 bit ones...
                                    string[] x64files = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");

                                    foreach (string str in x64files)
                                    {
                                        string destFile = System.IO.Path.Combine(exePath + "/Plugins/" + pluginFolder + "/", System.IO.Path.GetFileNameWithoutExtension(str));
                                        //Copy it to the new destination overwriting the old file if it exists
                                        System.IO.File.Copy(str, destFile, true);
                                    }
                                }
                            }

                            //Delete all the files with .x64 extensions since they aren't needed anymore
                            string[] delfiles = System.IO.Directory.GetFiles(exePath + "/Plugins/" + pluginFolder, "*.x64");
                            foreach (string str in delfiles)
                            {
                                System.IO.File.Delete(str);
                            }

                            this.Log.Info("Sending message to service to load plugin.");
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("catch: " + ex.Message);
                return(false);
            }
            if (Directory.Exists(exePath + "/tempDir/"))
            {
                deleteFolder(exePath + "/tempDir/");
            }

            OSAEMethodManager.MethodQueueAdd("SERVICE-" + Common.ComputerName, "RELOAD PLUGINS", "", "", "Plugin Installer");
            return(NoError);
        }
Ejemplo n.º 7
0
        private static void UpdateToLatestWorldDatabase(string dbURL, string dbFileName)
        {
            Console.WriteLine();

            if (IsRunningInContainer)
            {
                Console.WriteLine(" ");
                Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                Console.WriteLine(" ");
            }

            Console.Write($"Downloading {dbFileName} .... ");
            using (var client = new WebClient())
            {
                try
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                catch
                {
                    Console.Write($"Download for {dbFileName} failed!");
                    return;
                }
            }
            Console.WriteLine("download complete!");

            Console.Write($"Extracting {dbFileName} .... ");
            ZipFile.ExtractToDirectory(dbFileName, ".", true);
            Console.WriteLine("extraction complete!");
            Console.Write($"Deleting {dbFileName} .... ");
            File.Delete(dbFileName);
            Console.WriteLine("Deleted!");

            var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);

            Console.Write($"Importing {sqlFile} into SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} (This will take a while, please be patient) .... ");
            using (var sr = File.OpenText(sqlFile))
            {
                var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};password={ConfigManager.Config.MySql.World.Password};DefaultCommandTimeout=120");

                var line            = string.Empty;
                var completeSQLline = string.Empty;
                while ((line = sr.ReadLine()) != null)
                {
                    //do minimal amount of work here
                    if (line.EndsWith(";"))
                    {
                        completeSQLline += line + Environment.NewLine;

                        var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                        try
                        {
                            script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                            var count = script.Execute();
                        }
                        catch (MySql.Data.MySqlClient.MySqlException)
                        {
                        }
                        completeSQLline = string.Empty;
                    }
                    else
                    {
                        completeSQLline += line + Environment.NewLine;
                    }
                }
            }
            Console.WriteLine(" complete!");

            Console.Write($"Deleting {sqlFile} .... ");
            File.Delete(sqlFile);
            Console.WriteLine("Deleted!");
        }
Ejemplo n.º 8
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            Errors.Items.Clear();

            string   serverType = ServerTypeDrop.SelectedValue;
            DbServer serverTypeParsed;

            if (!Enum.TryParse <DbServer>(serverType, out serverTypeParsed))
            {
                Errors.Items.Add("Please, choose the type of database engine you wish to use.");
                return;
            }

            // initial testing of the database connection before we attempt to create the main schema
            IBaseDriver drv = null;

            switch (serverTypeParsed)
            {
            case DbServer.MySql:
                drv = new BaseDriverMySql(SystemConnstringTextBox.Text);
                break;

            case DbServer.MsSql:
                drv = new BaseDriverMsSql(SystemConnstringTextBox.Text);
                break;
            }

            try
            {
                drv.TestConnection();
                drv.TestDatabaseIsEmpty();
            }
            catch (Exception ex)
            {
                Errors.Items.Add(ex.Message);
                return;
            }

            if (UsernameTextBox.Text == "")
            {
                Errors.Items.Add("Please, insert the initial user's name");
                return;
            }

            if (PasswordTextBox.Text.Length < 7)
            {
                Errors.Items.Add("The password must be at least 7 characters long.");
                return;
            }

            if (PasswordTextBox.Text != RetypePasswordTextBox.Text)
            {
                Errors.Items.Add("The passwords do not match.");
                return;
            }

            try
            {
                System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(MailTextBox.Text);
            }
            catch (FormatException fe)
            {
                Errors.Items.Add(fe.Message);
                return;
            }


            // run the schema dump script
            switch (serverTypeParsed)
            {
            case DbServer.MySql:
                MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(SystemConnstringTextBox.Text);
                try
                {
                    MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection);
                    string scriptText = File.ReadAllText(HttpContext.Current.Server.MapPath(CC.MYSQL_SCHEMA_FILE_PATH));
                    script.Query = scriptText;
                    script.Query = scriptText;
                    connection.Open();
                    script.Execute();
                    connection.Clone();
                }
                catch (Exception esql1)
                {
                    Errors.Items.Add(esql1.Message);
                    connection.Close();
                    return;
                }
                break;

            case DbServer.MsSql:
                SqlConnection conn = new SqlConnection(SystemConnstringTextBox.Text);
                try
                {
                    string query = File.ReadAllText(HttpContext.Current.Server.MapPath(CC.MSSQL_SCHEMA_FILE_PATH));
                    Microsoft.SqlServer.Management.Smo.Server sqlServer = new Server(new ServerConnection(conn));
                    conn.Open();
                    sqlServer.ConnectionContext.ExecuteNonQuery(query);
                    conn.Close();

                    SqlMembershipProvider mssqlProvider = new SqlMembershipProvider();
                }
                catch (Exception esql2)
                {
                    Errors.Items.Add(esql2.Message);
                    conn.Close();
                    return;
                }
                break;
            }

            var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            var section       = (ConnectionStringsSection)configuration.GetSection("connectionStrings");

            System.Web.Security.MembershipProvider membership = null;

            string username = UsernameTextBox.Text;
            string password = PasswordTextBox.Text;
            string mail     = MailTextBox.Text;

            MembershipCreateStatus status;

            // rewrite the connection in the database and reload the connstring section, also set the defaultProvidder for the membership tag
            switch (serverTypeParsed)
            {
            case DbServer.MySql:
                section.ConnectionStrings["MySqlServer"].ConnectionString = SystemConnstringTextBox.Text;
                configuration.AppSettings.Settings["ServerType"].Value    = "MySql";
                configuration.Save();
                SetDefaultMembershipProvider("MySqlMembershipProvider");

                // remove the readonly attribute of the connection string variable of the connfiguration

                var settingsMy = ConfigurationManager.ConnectionStrings["MsSqlServer"];
                var fiMy       = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
                fiMy.SetValue(settingsMy, false);
                settingsMy.ConnectionString = SystemConnstringTextBox.Text;

                membership = Membership.Providers["MySqlMembershipProvider"];

                membership.CreateUser(username, password, mail, "Dummy question", "Dummy answer", true, 1, out status);
                break;


            case DbServer.MsSql:
                section.ConnectionStrings["MsSqlServer"].ConnectionString = SystemConnstringTextBox.Text;
                configuration.AppSettings.Settings["ServerType"].Value    = "MsSql";
                configuration.Save();
                SetDefaultMembershipProvider("MsSqlMembershipProvider");

                // remove the readonly attribute of the connection string variable of the connfiguration
                var settings = ConfigurationManager.ConnectionStrings["MsSqlServer"];
                var fi       = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
                fi.SetValue(settings, false);
                settings.ConnectionString = SystemConnstringTextBox.Text;

                membership = Membership.Providers["MsSqlMembershipProvider"];

                // generate a ProviderUserKey
                Random rand = new Random();
                Guid   key  = new Guid(rand.Next(), 2, 3, new byte[] { 10, 20, 30, 40, 50, 60, 70, 80 });
                ((SqlMembershipProvider)membership).CreateUser(username, password, mail, "Dummy question", "Dummy answer", true, key, out status);
                break;
            }

            int            totalUsers;
            MembershipUser user      = membership.FindUsersByName(username, 0, 1, out totalUsers)[username];
            SystemDriver   sysDriver = new SystemDriver(drv);

            sysDriver.SetUserRights((user.ProviderUserKey), null, 11110);


            // Set FirstRun to false. This cannot be done by the first configuration object - it wil
            // not like the configuration file since it has been modified by SetDefaultMembershipProvider
            // in the meantime.
            var config2 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

            config2.AppSettings.Settings["FirstRun"].Value = "False";
            System.Web.Configuration.WebConfigurationManager.AppSettings["FirstRun"] = "False";
            config2.Save();

            Errors.Items.Add("Done.");
            Response.RedirectToRoute("DefaultRoute");
        }
Ejemplo n.º 9
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            Errors.Items.Clear();

            string serverType = ServerTypeDrop.SelectedValue;
            DbServer serverTypeParsed;
            if (!Enum.TryParse<DbServer>(serverType, out serverTypeParsed))
            {
                Errors.Items.Add("Please, choose the type of database engine you wish to use.");
                return;
            }

            // initial testing of the database connection before we attempt to create the main schema
            IBaseDriver drv = null;
            switch (serverTypeParsed)
            {
                case DbServer.MySql:
                    drv = new BaseDriverMySql(SystemConnstringTextBox.Text);
                    break;
                case DbServer.MsSql:
                    drv = new BaseDriverMsSql(SystemConnstringTextBox.Text);
                    break;
            }

            try
            {
                drv.TestConnection();
                drv.TestDatabaseIsEmpty();
            }
            catch (Exception ex)
            {
                Errors.Items.Add(ex.Message);
                return;
            }

            if (UsernameTextBox.Text == "")
            {
                Errors.Items.Add("Please, insert the initial user's name");
                return;
            }

            if (PasswordTextBox.Text.Length < 7)
            {
                Errors.Items.Add("The password must be at least 7 characters long.");
                return;
            }

            if (PasswordTextBox.Text != RetypePasswordTextBox.Text)
            {
                Errors.Items.Add("The passwords do not match.");
                return;
            }

            try
            {
                System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(MailTextBox.Text);
            }
            catch (FormatException fe)
            {
                Errors.Items.Add(fe.Message);
                return;
            }

            // run the schema dump script
            switch (serverTypeParsed)
            {
                case DbServer.MySql:
                    MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(SystemConnstringTextBox.Text);
                    try
                    {
                        MySql.Data.MySqlClient.MySqlScript script = new MySql.Data.MySqlClient.MySqlScript(connection);
                        string scriptText = File.ReadAllText(HttpContext.Current.Server.MapPath(CC.MYSQL_SCHEMA_FILE_PATH));
                        script.Query = scriptText;
                        script.Query = scriptText;
                        connection.Open();
                        script.Execute();
                        connection.Clone();
                    }
                    catch (Exception esql1)
                    {
                        Errors.Items.Add(esql1.Message);
                        connection.Close();
                        return;
                    }
                    break;

                case DbServer.MsSql:
                    SqlConnection conn = new SqlConnection(SystemConnstringTextBox.Text);
                    try
                    {

                        string query = File.ReadAllText(HttpContext.Current.Server.MapPath(CC.MSSQL_SCHEMA_FILE_PATH));
                        Microsoft.SqlServer.Management.Smo.Server sqlServer = new Server(new ServerConnection(conn));
                        conn.Open();
                        sqlServer.ConnectionContext.ExecuteNonQuery(query);
                        conn.Close();

                        SqlMembershipProvider mssqlProvider = new SqlMembershipProvider();

                    }
                    catch (Exception esql2)
                    {
                        Errors.Items.Add(esql2.Message);
                        conn.Close();
                        return;
                    }
                    break;
            }

            var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");

            System.Web.Security.MembershipProvider membership = null;

            string username = UsernameTextBox.Text;
            string password = PasswordTextBox.Text;
            string mail = MailTextBox.Text;

            MembershipCreateStatus status;

            // rewrite the connection in the database and reload the connstring section, also set the defaultProvidder for the membership tag
            switch (serverTypeParsed)
            {
                case DbServer.MySql:
                    section.ConnectionStrings["MySqlServer"].ConnectionString = SystemConnstringTextBox.Text;
                    configuration.AppSettings.Settings["ServerType"].Value = "MySql";
                    configuration.Save();
                    SetDefaultMembershipProvider("MySqlMembershipProvider");

                    // remove the readonly attribute of the connection string variable of the connfiguration

                    var settingsMy = ConfigurationManager.ConnectionStrings["MsSqlServer"];
                    var fiMy = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
                    fiMy.SetValue(settingsMy, false);
                    settingsMy.ConnectionString = SystemConnstringTextBox.Text;

                    membership = Membership.Providers["MySqlMembershipProvider"];

                    membership.CreateUser(username, password, mail, "Dummy question", "Dummy answer", true, 1, out status);
                    break;

                case DbServer.MsSql:
                    section.ConnectionStrings["MsSqlServer"].ConnectionString = SystemConnstringTextBox.Text;
                    configuration.AppSettings.Settings["ServerType"].Value = "MsSql";
                    configuration.Save();
                    SetDefaultMembershipProvider("MsSqlMembershipProvider");

                    // remove the readonly attribute of the connection string variable of the connfiguration
                    var settings = ConfigurationManager.ConnectionStrings["MsSqlServer"];
                    var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
                    fi.SetValue(settings, false);
                    settings.ConnectionString = SystemConnstringTextBox.Text;

                    membership = Membership.Providers["MsSqlMembershipProvider"];

                    // generate a ProviderUserKey
                    Random rand = new Random();
                    Guid key = new Guid(rand.Next(), 2, 3, new byte[] { 10, 20, 30, 40, 50, 60, 70, 80 });
                    ((SqlMembershipProvider)membership).CreateUser(username, password, mail, "Dummy question", "Dummy answer", true, key, out status);
                    break;
            }

            int totalUsers;
            MembershipUser user = membership.FindUsersByName(username, 0, 1, out totalUsers)[username];
            SystemDriver sysDriver = new SystemDriver(drv);
            sysDriver.SetUserRights((user.ProviderUserKey), null, 11110);

            // Set FirstRun to false. This cannot be done by the first configuration object - it wil
            // not like the configuration file since it has been modified by SetDefaultMembershipProvider
            // in the meantime.
            var config2 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            config2.AppSettings.Settings["FirstRun"].Value = "False";
            System.Web.Configuration.WebConfigurationManager.AppSettings["FirstRun"] = "False";
            config2.Save();

            Errors.Items.Add("Done.");
            Response.RedirectToRoute("DefaultRoute");
        }