public void SafeTryGetValue()
 {
     object obj;
       MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder("server=localhost;");
       s.TryGetValue("unknownproperty", out obj);
       Assert.AreEqual(null, obj);
 }
 public void NoValueGivenForConnectionStringOption()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder();
     s.ConnectionString = "compress=;pooling=";
     Assert.IsFalse(s.UseCompression);
     Assert.IsTrue(s.Pooling);
 }
 public void SettingValueMultipeTimes()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder();
     s["database"] = "test";
     s["database"] = "test2";
     Assert.AreEqual("database=test2", s.ConnectionString);
 }
    private static string GetKey(MySqlConnectionStringBuilder settings)
    {
      string key = "";
      lock (settings)
      {
        key = settings.ConnectionString;
      }
#if !NETSTANDARD1_6
      if (settings.IntegratedSecurity && !settings.ConnectionReset)
      {
        try
        {
          // Append SID to the connection string to generate a key
          // With Integrated security different Windows users with the same
          // connection string may be mapped to different MySQL accounts.
          System.Security.Principal.WindowsIdentity id =
            System.Security.Principal.WindowsIdentity.GetCurrent();

          key += ";" + id.User;
        }
        catch (System.Security.SecurityException ex)
        {
          // Documentation for WindowsIdentity.GetCurrent() states 
          // SecurityException can be thrown. In this case the 
          // connection can only be pooled if reset is done.
          throw new MySqlException(Resources.NoWindowsIdentity, ex);
        }
      }
#endif
            return key;
    }
Пример #5
0
    private static Stream GetUnixSocketStream(MySqlConnectionStringBuilder settings)
    {
      if (Platform.IsWindows())
        throw new InvalidOperationException(Resources.NoUnixSocketsOnWindows);

      MyNetworkStream s = MyNetworkStream.CreateStream(settings, true);
      return s;
    }
Пример #6
0
 public static Stream GetStream(string server, uint port, string pipename, uint keepalive, DBVersion v, uint timeout)
 {
     MySqlConnectionStringBuilder settings = new MySqlConnectionStringBuilder();
     settings.Server = server;
     settings.Port = port;
     settings.PipeName = pipename;
     settings.Keepalive = keepalive;
     settings.ConnectionTimeout = timeout;
     return GetStream(settings);
 }
 public MyCatRelationalConnection CreateMasterConnection()
 {
     var csb = new MySqlConnectionStringBuilder(ConnectionString) {
         Database = "MyCat",
         Pooling = false
     };
     
     var optionsBuilder = new DbContextOptionsBuilder();
     optionsBuilder.UseMyCat(csb.GetConnectionString(true));
     return new MyCatRelationalConnection(optionsBuilder.Options, Logger);
 }
Пример #8
0
 public Driver(MySqlConnectionStringBuilder settings)
 {
     encoding = Encoding.UTF8;
     if (encoding == null)
         throw new MySqlException(Resources.DefaultEncodingNotFound);
     connectionString = settings;
     serverCharSet = "latin1";
     serverCharSetIndex = -1;
     maxPacketSize = 1024;
     handler = new NativeDriver(this);
 }
    public void Simple()
    {
      MySqlConnectionStringBuilder sb = null;
      sb = new MySqlConnectionStringBuilder();
      sb.ConnectionString = "server=localhost;uid=reggie;pwd=pass;port=1111;" +
          "connection timeout=23; pooling=true; min pool size=33; " +
          "max pool size=66;keepalive=1";
      Assert.AreEqual("localhost", sb.Server);
      Assert.AreEqual("reggie", sb.UserID);
      Assert.AreEqual("pass", sb.Password);
      Assert.AreEqual(1111, sb.Port);
      Assert.AreEqual(23, sb.ConnectionTimeout);
      Assert.IsTrue(sb.Pooling);
      Assert.AreEqual(33, sb.MinimumPoolSize);
      Assert.AreEqual(66, sb.MaximumPoolSize);
      Assert.AreEqual(sb.Keepalive, 1);

      try
      {
        sb.ConnectionString = "server=localhost;badkey=badvalue";
        Assert.Fail("This should not work");
      }
      catch (ArgumentException)
      {
      }

      sb.Clear();
      Assert.AreEqual(15, sb.ConnectionTimeout);
      Assert.AreEqual(true, sb.Pooling);
      Assert.AreEqual(3306, sb.Port);
      Assert.AreEqual(String.Empty, sb.Server);
      Assert.AreEqual(false, sb.PersistSecurityInfo);
      Assert.AreEqual(0, sb.ConnectionLifeTime);
      Assert.IsFalse(sb.ConnectionReset);
      Assert.AreEqual(0, sb.MinimumPoolSize);
      Assert.AreEqual(100, sb.MaximumPoolSize);
      Assert.AreEqual(String.Empty, sb.UserID);
      Assert.AreEqual(String.Empty, sb.Password);
      Assert.AreEqual(false, sb.UseUsageAdvisor);
      Assert.AreEqual(String.Empty, sb.CharacterSet);
      Assert.AreEqual(false, sb.UseCompression);
      Assert.AreEqual("MYSQL", sb.PipeName);
      Assert.IsFalse(sb.Logging);
      Assert.IsFalse(sb.UseOldSyntax);
      Assert.IsTrue(sb.AllowBatch);
      Assert.IsFalse(sb.ConvertZeroDateTime);
      Assert.AreEqual("MYSQL", sb.SharedMemoryName);
      Assert.AreEqual(String.Empty, sb.Database);
      Assert.AreEqual(MySqlConnectionProtocol.Sockets, sb.ConnectionProtocol);
      Assert.IsFalse(sb.AllowZeroDateTime);
      Assert.IsFalse(sb.UsePerformanceMonitor);
      Assert.AreEqual(25, sb.ProcedureCacheSize);
      Assert.AreEqual(0, sb.Keepalive);
    }
Пример #10
0
        public void WaitTimeoutExpiring()
        {
            string connStr = GetConnectionString(true);
            MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr);

            if (sb.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe)
                // wait timeout does not work for named pipe connections
                return;

            using (MySqlConnection c = new MySqlConnection(connStr))
            {
                c.Open();
                c.StateChange += new StateChangeEventHandler(c_StateChange);

                // set the session wait timeout on this new connection
                MySqlCommand cmd = new MySqlCommand("SET SESSION interactive_timeout=3", c);
                cmd.ExecuteNonQuery();
                cmd.CommandText = "SET SESSION wait_timeout=2";
                cmd.ExecuteNonQuery();

                stateChangeCount = 0;
                // now wait 4 seconds
                Thread.Sleep(4000);

                try
                {
                    cmd.CommandText = "SELECT now()";
                    cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex.Message.StartsWith("Fatal"));
                }

                Assert.AreEqual(1, stateChangeCount);
                Assert.AreEqual(ConnectionState.Closed, c.State);
            }

            using (MySqlConnection c = new MySqlConnection(connStr))
            {
                c.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT now() as thetime, database() as db", c);
                using (MySqlDataReader r = cmd.ExecuteReader())
                {
                    Assert.IsTrue(r.Read());
                }
            }
        }
    public static MySqlPool GetPool(MySqlConnectionStringBuilder settings)
    {
      string text = GetKey(settings);

      lock (pools)
      {
        MySqlPool pool;
        pools.TryGetValue(text, out pool);

        if (pool == null)
        {
          pool = new MySqlPool(settings);
          pools.Add(text, pool);
        }
        else
          pool.Settings = settings;

        return pool;
      }
    }
Пример #12
0
    public MySqlPool(MySqlConnectionStringBuilder settings)
    {
      minSize = settings.MinimumPoolSize;
      maxSize = settings.MaximumPoolSize;

      available = (int)maxSize;
      autoEvent = new AutoResetEvent(false);

      if (minSize > maxSize)
        minSize = maxSize;
      this.settings = settings;
      inUsePool = new List<Driver>((int)maxSize);
      idlePool = new Queue<Driver>((int)maxSize);

      // prepopulate the idle pool to minSize
      for (int i = 0; i < minSize; i++)
        EnqueueIdle(CreateNewPooledConnection());

      procedureCache = new ProcedureCache((int)settings.ProcedureCacheSize);
    }
Пример #13
0
        public static Stream GetStream(MySqlConnectionStringBuilder settings)
        {
            switch (settings.ConnectionProtocol)
            {
                case MySqlConnectionProtocol.Tcp: return GetTcpStream(settings);
#if RT
        case MySqlConnectionProtocol.UnixSocket: throw new NotImplementedException();
        case MySqlConnectionProtocol.SharedMemory: throw new NotImplementedException();
#else
#if !NETSTANDARD1_6
        case MySqlConnectionProtocol.UnixSocket: return GetUnixSocketStream(settings);        
        case MySqlConnectionProtocol.SharedMemory: return GetSharedMemoryStream(settings);
#endif

#endif
#if !NETSTANDARD1_6
                case MySqlConnectionProtocol.NamedPipe: return GetNamedPipeStream(settings);
#endif
            }
            throw new InvalidOperationException(Resources.UnknownConnectionProtocol);
        }
Пример #14
0
        internal BootResult Boot(string configPath)
        {
            try
            {
                _textEncoding = Encoding.UTF8; // TODO: Move this to an external config.

                #region Standard Out

                _standardOut = new StandardOut();
                _standardOut.PrintNotice("Text Encoding => Set to " + _textEncoding.EncodingName);
                _standardOut.PrintNotice("Standard Out => Ready");

                #endregion

                _config = new XmlConfig(configPath);

                bool mainInstallRequired = PreInstall(); // Register the main installation if required.

                #region Load Plugins

                _standardOut.PrintNotice("Plugin Manager => Loading plugins...");
                _pluginManager = new PluginManager();

                XmlNodeList pluginNodes = GetConfig().GetInternalDocument().SelectNodes("/config/plugins/plugin");
                foreach (XmlNode pluginNode in pluginNodes)
                {
                    GetPluginManager().LoadPluginAtPath(
                        Path.Combine(
                            Directory.GetCurrentDirectory(),
                            "plugins",
                            pluginNode.Attributes["filename"].InnerText));
                }
                _standardOut.PrintNotice("Plugin Manager => Plugins loaded!");

                #endregion

                CoreManager.InstallerCore.Run();

                if (mainInstallRequired)
                {
                    SaveConfigInstallation();
                }

                #region Config

                _standardOut.PrintNotice("Config File => Loaded");
                _standardOut.SetImportance(
                    (StandardOutImportance)
                    _config.ValueAsByte("/config/standardout/importance", (byte)StandardOutImportance.Debug));

                #endregion

                #region Database

                _standardOut.PrintNotice("MySQL => Preparing database connection settings...");

                try
                {
                    MySqlConnectionStringBuilder connectionString = new MySqlConnectionStringBuilder
                    {
                        Server =
                            _config.ValueAsString(
                                "/config/mysql/host"),
                        Port =
                            _config.ValueAsUint(
                                "/config/mysql/port", 3306),
                        UserID =
                            _config.ValueAsString(
                                "/config/mysql/user"),
                        Password =
                            _config.ValueAsString(
                                "/config/mysql/password"),
                        Database =
                            _config.ValueAsString(
                                "/config/mysql/database"),
                        Pooling         = true,
                        MinimumPoolSize =
                            _config.ValueAsUint(
                                "/config/mysql/minpoolsize", 1),
                        MaximumPoolSize =
                            _config.ValueAsUint(
                                "/config/mysql/maxpoolsize", 25)
                    };

                    PrepareSessionFactory(connectionString.ConnectionString);

                    _standardOut.PrintNotice("MySQL => Testing connection...");

                    using (ISession db = GetDatabaseSession())
                    {
                        if (!db.IsConnected)
                        {
                            throw new Exception("Unknown cause");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _standardOut.PrintError("MySQL => Connection failed!");
                    throw;
                }
                _standardOut.PrintNotice("MySQL => Connected!");

                #endregion

                #region Distributors

                _standardOut.PrintNotice("Habbo Distributor => Constructing...");
                _habboDistributor = new HabboDistributor();
                _standardOut.PrintNotice("Habbo Distributor => Ready");

                #endregion

                #region Figure Factory

                _standardOut.PrintNotice("Habbo Figure Factory => Constructing...");
                _habboFigureFactory = new HabboFigureFactory();
                _standardOut.PrintNotice("Habbo Figure Factory => Ready");

                #endregion

                // TODO: Download Requirements

                #region Permissions

                _standardOut.PrintNotice("Permission Manager => Constructing...");
                _permissionManager = new PermissionManager();
                _standardOut.PrintNotice("Permission Manager => Ready");

                #endregion

                // TODO: Write Dynamic Client Files
                // TODO: Authenticate with IHINet

                #region Network

                _standardOut.PrintNotice("Connection Manager => Starting...");
                _connectionManager = new IonTcpConnectionManager(_config.ValueAsString("/config/network/host"),
                                                                 _config.ValueAsInt("/config/network/port", 14478));
                _connectionManager.GetListener().Start();
                _standardOut.PrintNotice("Connection Manager => Ready!");

                _standardOut.PrintNotice("Web Admin => Starting...");
                _webAdminManager = new WebAdminManager(_config.ValueAsUshort("/config/webadmin/port", 14480));
                _standardOut.PrintNotice("Web Admin => Ready!");

                #endregion

                #region Start Plugins

                PluginManager pluginManager = GetPluginManager();
                _standardOut.PrintNotice("Plugin Manager => Starting plugins...");

                foreach (Plugin plugin in pluginManager.GetLoadedPlugins())
                {
                    pluginManager.StartPlugin(plugin);
                }
                _standardOut.PrintNotice("Plugin Manager => Plugins started!");

                #endregion

                _standardOut.PrintImportant("IHI is now functional!");

                return(BootResult.AllClear);
            }
            catch (Exception e)
            {
                _standardOut.PrintException(e);


                if (e is MappingException)
                {
                    return(BootResult.MySQLMappingFailure);
                }

                return(BootResult.UnknownFailure);
            }
        }
Пример #15
0
        public static Driver Create(MySqlConnectionStringBuilder settings)
        {
            Driver d = null;
#if !NETSTANDARD1_6
            try
            {
                if (MySqlTrace.QueryAnalysisEnabled || settings.Logging || settings.UseUsageAdvisor)
                    d = new TracingDriver(settings);
            }
            catch (TypeInitializationException ex)
            {
                if (!(ex.InnerException is SecurityException))
                    throw ex;
                //Only rethrow if InnerException is not a SecurityException. If it is a SecurityException then 
                //we couldn't initialize MySqlTrace because we don't have unmanaged code permissions. 
            }
#else
      if (settings.Logging || settings.UseUsageAdvisor)
      {
        throw new NotImplementedException( "Logging not supported in this WinRT release." );
      }
#endif
            if (d == null)
                d = new Driver(settings);

            //this try was added as suggested fix submitted on MySql Bug 72025, socket connections are left in CLOSE_WAIT status when connector fails to open a new connection.
            //the bug is present when the client try to get more connections that the server support or has configured in the max_connections variable.
            try
            {
                d.Open();
            }
            catch (Exception ex)
            {
                d.Dispose();
                throw ex;
            }
            return d;
        }
Пример #16
0
        public static RegDatabase LoadDatabase()
        {
            regDb = new RegDatabase();

            MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();

            conn_string.Server = "enki";
            //conn_string.Server = "rowantree.org";
            conn_string.UserID   = "rowan_RosReg";
            conn_string.Password = "******";
            conn_string.Database = "rowan_RitesRegistration";
            //conn_string.SslMode = MySqlSslMode.Required;

            log.InfoFormat("Loading data from MySql Server:{0} ", conn_string.Server);

            using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
            {
                conn.Open();

                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT (SELECT count(*) FROM registration) RegCnt, (SELECT count(*) FROM person) PeopleCnt";
                    using (MySqlDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            regDb.RegCount    = rdr.GetInt32(0);
                            regDb.PersonCount = rdr.GetInt32(1);
                        }
                    }
                }

                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT * FROM registration";
                    using (MySqlDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            regDb.regData.Add(new Registration(rdr));
                        }
                    }
                }

                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT * FROM person";
                    using (MySqlDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            Person person = new Person(rdr);
                            regDb.personData.Add(person);
                            Registration reg = regDb.regData.FirstOrDefault(x => x.RegId == person.regID);
                            reg.personList.Add(person);
                            //regDb.regData.First(x => x.RegId == person.regID).personList.Add(person);
                        }
                    }
                }

                using (MySqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT * FROM merchant";
                    using (MySqlDataReader rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            Merchant merchant = new Merchant(rdr);
                            regDb.merchantData.Add(merchant);
                            Registration reg = regDb.regData.FirstOrDefault(x => x.RegId == merchant.regID);
                            if (reg != null)
                            {
                                reg.merchantInfo = merchant;
                            }
                            else
                            {
                                // this is an error
                            }
                        }
                    }
                }
            }

            log.InfoFormat("Loaded {0} Registration {1} Person {2} Merchant Records", regDb.regData.Count, regDb.personData.Count, regDb.merchantData.Count);

            return(regDb);
        }
    /// <summary>
    /// Assigns a new server driver to the connection object
    /// </summary>
    /// <param name="groupName">Group name</param>
    /// <param name="master">True if the server connection to assign must be a master</param>
    /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
    internal static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
    {
      do
      {
        lock (thisLock)
        {
          if (!IsReplicationGroup(groupName)) return;

          ReplicationServerGroup group = GetGroup(groupName);
          ReplicationServer server = group.GetServer(master, connection.Settings);

          if (server == null)
            throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);

          try
          {
            bool isNewServer = false;
            if (connection.driver == null || !connection.driver.IsOpen)
            {
              isNewServer = true;
            }
            else
            { 
              MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(server.ConnectionString);
              if (!msb.Equals(connection.driver.Settings))
              {
                isNewServer = true;
              }
            }
            if (isNewServer)
            {
              Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
              connection.driver = driver;
            }
            return;
          }
          catch (MySqlException ex)
          {
            connection.driver = null;
            server.IsAvailable = false;
            MySqlTrace.LogError(ex.Number, ex.ToString());
            if (ex.Number == 1042)
            {
              // retry to open a failed connection and update its status
              group.HandleFailover(server, ex);
            }
            else
              throw;
          }
        }
      } while (true);
    }
 public void EncrpytSslmode()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder("server=localhost;encrypt=true");
     Assert.AreEqual(s.SslMode, MySqlSslMode.Preferred);
 }
Пример #19
0
        public void ConnectionStringModifiedAfterCancel()
        {
            if (Version.Major < 5) return;

            string connStr = GetPoolingConnectionString();
            MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr);

            if (sb.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe)
                // idle named pipe connections cannot be KILLed (server bug#47571)
                return;

            connStr = connStr.Replace("persist security info=true", "persist security info=false");

            int threadId;
            using (MySqlConnection c = new MySqlConnection(connStr))
            {
                c.Open();
                threadId = c.ServerThread;
                string connStr1 = c.ConnectionString;

                MySqlCommand cmd = new MySqlCommand("SELECT SLEEP(2)", c);
                cmd.CommandTimeout = 1;

                try
                {
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                    }
                }
                catch (MySqlException ex)
                {
                    Assert.IsTrue(ex.InnerException is TimeoutException);
                    Assert.IsTrue(c.State == ConnectionState.Open);
                }
                string connStr2 = c.ConnectionString.ToLower(CultureInfo.InvariantCulture);
                Assert.AreEqual(connStr1.ToLower(CultureInfo.InvariantCulture), connStr2);
            }
            execSQL("kill " + threadId);
        }
Пример #20
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtNombre.Text != "")
                {
                    this.Enabled = false;
                    MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
                    builder.Server   = "31.170.166.58";
                    builder.UserID   = "u215283317_pb";
                    builder.Password = "******";
                    builder.Database = "u215283317_pb";
                    MySqlConnection conn         = new MySqlConnection(builder.ToString());
                    MySqlCommand    cmd          = conn.CreateCommand();
                    string          nombreServer = txtNombre.Text + "_" + DateTime.Now.ToString().Replace(' ', '_');
                    nombreServer = nombreServer.Replace('/', '_');
                    string tabla = "";
                    if (checkBox1.Checked)
                    {
                        tabla = "archivostrabajadores (trabajador_id, ";
                    }
                    else
                    {
                        tabla = "archivos (cliente_id, ";
                    }
                    cmd.CommandText =
                        "INSERT INTO " + tabla + "nombre, nombre_servidor, descripcion, observaciones, extension, visible) value ('" +
                        cbClientes.SelectedItem.ToString().Split(',')[0] + "', '" + txtNombre.Text + ".pdf', '" + nombreServer + ".pdf', '" + txtDescripcion.Text + "', '"
                        + txtObservaciones.Text + "', '.pdf', 'si')";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    guardarPDF(txtNombre.Text);
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.abogadosynotariosroldan.com/" + nombreServer + ".pdf");
                    request.Method      = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential("u215283317.remoto", "abogadosroldan");
                    StreamReader sourceStream = new StreamReader(carpeta + txtNombre.Text + ".pdf");
                    byte[]       fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                    sourceStream.Close();
                    request.ContentLength = fileContents.Length;

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(fileContents, 0, fileContents.Length);
                    requestStream.Close();

                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                    Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

                    response.Close();
                    MessageBox.Show("Archivo cargado con éxito", "Operación exitosa", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Debe llenar el campo Nombre para continuar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                this.Enabled = true;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
Пример #21
0
        public void ClearPool()
        {
            string connStr = GetPoolingConnectionString() + ";min pool size=10";
            MySqlConnectionStringBuilder settings = new MySqlConnectionStringBuilder(connStr);
            MySqlConnection[] connections = new MySqlConnection[10];
            connections[0] = new MySqlConnection(connStr);
            connections[0].Open();

            string assemblyName = typeof(MySqlConnection).GetTypeInfo().Assembly.FullName;
            string pmName = String.Format("MySql.Data.MySqlClient.MySqlPoolManager, {0}", assemblyName);

            Type poolManager = Type.GetType(pmName, false);
            FieldInfo poolManagerHashTable = poolManager.GetField("pools",
                BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            Hashtable poolHash = (Hashtable)poolManagerHashTable.GetValue(null);
            FieldInfo clearingPoolsFI = poolManager.GetField("clearingPools",
                BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            ICollection clearingPools = (ICollection)clearingPoolsFI.GetValue(null);

            // now we need to investigate
            string poolName = String.Format("MySql.Data.MySqlClient.MySqlPool, {0}", assemblyName);
            Type poolType = Type.GetType(poolName, false);

            FieldInfo inUsePool = poolType.GetField("inUsePool", BindingFlags.NonPublic | BindingFlags.Instance);
            ICollection inUseList = (ICollection)inUsePool.GetValue(poolHash[settings.ConnectionString]);
            Assert.AreEqual(1, inUseList.Count);

            FieldInfo idlePool = poolType.GetField("idlePool", BindingFlags.NonPublic | BindingFlags.Instance);
            ICollection idleList = (ICollection)idlePool.GetValue(poolHash[settings.ConnectionString]);
            Assert.AreEqual(9, idleList.Count);

            // now open 4 more of these.  Now we shoudl have 5 open and five
            // still in the pool
            for (int i = 1; i < 5; i++)
            {
                connections[i] = new MySqlConnection(connStr);
                connections[i].Open();
            }

            Assert.AreEqual(5, inUseList.Count);
            Assert.AreEqual(5, idleList.Count);

            Assert.AreEqual(0, clearingPools.Count);
            // now tell this connection to clear its pool
            MySqlConnection.ClearPool(connections[0]);
            Assert.AreEqual(1, clearingPools.Count);
            Assert.AreEqual(0, idleList.Count);

            for (int i = 0; i < 5; i++)
                connections[i].Close();
            Assert.AreEqual(0, clearingPools.Count);
        }
Пример #22
0
        public static void Initialize()
        {
            ServerStarted           = DateTime.Now;
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine();
            Console.WriteLine("                     ____  __           ________  _____  __");
            Console.WriteLine(@"                    / __ \/ /_  _______/ ____/  |/  / / / /");
            Console.WriteLine("                   / /_/ / / / / / ___/ __/ / /|_/ / / / / ");
            Console.WriteLine("                  / ____/ / /_/ (__  ) /___/ /  / / /_/ /  ");
            Console.WriteLine(@"                 /_/   /_/\__,_/____/_____/_/  /_/\____/ ");

            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("                                " + PrettyVersion + " <Build " + PrettyBuild + ">");
            Console.WriteLine("                                http://PlusIndustry.com");

            Console.WriteLine("");
            Console.Title    = "Loading Plus Emulator";
            _defaultEncoding = Encoding.Default;

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

            CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");

            try
            {
                string projectSolutionPath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));

                _configuration = new ConfigurationData("./Config/config.ini");

                var connectionString = new MySqlConnectionStringBuilder
                {
                    ConnectionTimeout     = 10,
                    Database              = GetConfig().data["db.name"],
                    DefaultCommandTimeout = 30,
                    Logging             = false,
                    MaximumPoolSize     = uint.Parse(GetConfig().data["db.pool.maxsize"]),
                    MinimumPoolSize     = uint.Parse(GetConfig().data["db.pool.minsize"]),
                    Password            = GetConfig().data["db.password"],
                    Pooling             = true,
                    Port                = uint.Parse(GetConfig().data["db.port"]),
                    Server              = GetConfig().data["db.hostname"],
                    UserID              = GetConfig().data["db.username"],
                    AllowZeroDateTime   = true,
                    ConvertZeroDateTime = true,
                    SslMode             = MySqlSslMode.None
                };

                _manager = new DatabaseManager(connectionString.ToString());

                if (!_manager.IsConnected())
                {
                    log.Error("Failed to Connect to the specified MySQL server.");
                    Console.ReadKey(true);
                    Environment.Exit(1);
                    return;
                }

                log.Info("Connected to Database!");

                //Reset our statistics first.
                using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
                    dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';");
                    dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'");
                    dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
                }

                //Get the configuration & Game set.
                _languageManager = new LanguageManager();
                _languageManager.Init();

                _settingsManager = new SettingsManager();
                _settingsManager.Init();

                _figureManager = new FigureDataManager();
                _figureManager.Init();

                //Have our encryption ready.
                HabboEncryptionV2.Initialize(new RSAKeys());

                //Make sure Rcon is connected before we allow clients to Connect.
                _Rcon = new RconSocket(GetConfig().data["rcon.tcp.bindip"], int.Parse(GetConfig().data["rcon.tcp.port"]), GetConfig().data["rcon.tcp.allowedaddr"].Split(Convert.ToChar(";")));

                _game = new Game();
                _game.StartGameLoop();

                //Accept connections.
                _bootstrap = new NetworkBootstrap(GetConfig().data["game.tcp.bindip"], int.Parse(GetConfig().data["game.tcp.port"]));
                _bootstrap.InitAsync().Wait();

                TimeSpan TimeUsed = DateTime.Now - ServerStarted;

                Console.WriteLine();

                log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
            }
#pragma warning disable CS0168 // The variable 'e' is declared but never used
            catch (KeyNotFoundException e)
#pragma warning restore CS0168 // The variable 'e' is declared but never used
            {
                log.Error("Please check your configuration file - some values appear to be missing.");
                log.Error("Press any key to shut down ...");

                Console.ReadKey(true);
                Environment.Exit(1);
                return;
            }
            catch (InvalidOperationException e)
            {
                log.Error("Failed to initialize PlusEmulator: " + e.Message);
                log.Error("Press any key to shut down ...");
                Console.ReadKey(true);
                Environment.Exit(1);
                return;
            }
            catch (Exception e)
            {
                log.Error("Fatal error during startup: " + e);
                log.Error("Press a key to exit");

                Console.ReadKey();
                Environment.Exit(1);
            }
        }
 internal override void AdjustConnectionSettings(MySqlConnectionStringBuilder settings)
 {
     settings.ConnectionProtocol = MySqlConnectionProtocol.NamedPipe;
     settings.UseCompression     = true;
     settings.SslMode            = MySqlSslMode.None;
 }
Пример #24
0
 public ExternalAuthenticationPlugin(MySqlConnectionStringBuilder settings)
 {
     _settings = settings;
 }
        public void ParseConnectionString()
        {
            var csb = new MySqlConnectionStringBuilder
            {
                ConnectionString = "Data Source=db-server;" +
                                   "Initial Catalog=schema_name;" +
                                   "allow load local infile=true;" +
                                   "allowpublickeyretrieval = true;" +
                                   "Allow User Variables=true;" +
                                   "allow zero datetime=true;" +
                                   "auto enlist=False;" +
                                   "certificate file=file.pfx;" +
                                   "certificate password=Pass1234;" +
                                   "certificate store location=CurrentUser;" +
                                   "certificate thumb print=thumbprint123;" +
                                   "Character Set=latin1;" +
                                   "Compress=true;" +
                                   "connect timeout=30;" +
                                   "connection lifetime=15;" +
                                   "ConnectionReset=false;" +
                                   "Convert Zero Datetime=true;" +
#if !BASELINE
                                   "datetimekind=utc;" +
#endif
                                   "default command timeout=123;" +
#if !BASELINE
                                   "application name=My Test Application;" +
                                   "connection idle ping time=60;" +
                                   "connectionidletimeout=30;" +
                                   "forcesynchronous=true;" +
                                   "ignore command transaction=true;" +
                                   "server rsa public key file=rsa.pem;" +
                                   "load balance=random;" +
                                   "guidformat=timeswapbinary16;" +
                                   "nobackslashescapes=true;" +
                                   "server spn=mariadb/[email protected];" +
                                   "use xa transactions=false;" +
#endif
                                   "ignore prepare=false;" +
                                   "interactive=true;" +
                                   "Keep Alive=90;" +
                                   "minpoolsize=5;" +
                                   "maxpoolsize=15;" +
                                   "OldGuids=true;" +
                                   "persistsecurityinfo=yes;" +
                                   "Pipe=MyPipe;" +
                                   "Pooling=no;" +
                                   "Port=1234;" +
                                   "protocol=pipe;" +
                                   "pwd=Pass1234;" +
                                   "Treat Tiny As Boolean=false;" +
                                   "ssl-ca=ca.pem;" +
                                   "ssl-cert=client-cert.pem;" +
                                   "ssl-key=client-key.pem;" +
                                   "ssl mode=verifyca;" +
                                   "Uid=username;" +
                                   "useaffectedrows=true"
            };

            Assert.True(csb.AllowLoadLocalInfile);
            Assert.True(csb.AllowPublicKeyRetrieval);
            Assert.True(csb.AllowUserVariables);
            Assert.True(csb.AllowZeroDateTime);
            Assert.False(csb.AutoEnlist);
#if !BASELINE
            // Connector/NET treats "CertificateFile" (client certificate) and "SslCa" (server CA) as aliases
            Assert.Equal("file.pfx", csb.CertificateFile);
#endif
            Assert.Equal("Pass1234", csb.CertificatePassword);
            Assert.Equal(MySqlCertificateStoreLocation.CurrentUser, csb.CertificateStoreLocation);
            Assert.Equal("thumbprint123", csb.CertificateThumbprint);
            Assert.Equal("latin1", csb.CharacterSet);
            Assert.Equal(15u, csb.ConnectionLifeTime);
            Assert.Equal(MySqlConnectionProtocol.NamedPipe, csb.ConnectionProtocol);
            Assert.False(csb.ConnectionReset);
            Assert.Equal(30u, csb.ConnectionTimeout);
            Assert.True(csb.ConvertZeroDateTime);
#if !BASELINE
            Assert.Equal(MySqlDateTimeKind.Utc, csb.DateTimeKind);
#endif
            Assert.Equal("schema_name", csb.Database);
            Assert.Equal(123u, csb.DefaultCommandTimeout);
#if !BASELINE
            Assert.Equal("My Test Application", csb.ApplicationName);
            Assert.Equal(60u, csb.ConnectionIdlePingTime);
            Assert.Equal(30u, csb.ConnectionIdleTimeout);
            Assert.True(csb.ForceSynchronous);
            Assert.True(csb.IgnoreCommandTransaction);
            Assert.Equal("rsa.pem", csb.ServerRsaPublicKeyFile);
            Assert.Equal(MySqlLoadBalance.Random, csb.LoadBalance);
            Assert.Equal(MySqlGuidFormat.TimeSwapBinary16, csb.GuidFormat);
            Assert.True(csb.NoBackslashEscapes);
            Assert.Equal("mariadb/[email protected]", csb.ServerSPN);
            Assert.False(csb.UseXaTransactions);
#endif
            Assert.False(csb.IgnorePrepare);
            Assert.True(csb.InteractiveSession);
            Assert.Equal(90u, csb.Keepalive);
            Assert.Equal(15u, csb.MaximumPoolSize);
            Assert.Equal(5u, csb.MinimumPoolSize);
            Assert.Equal("Pass1234", csb.Password);
            Assert.Equal("MyPipe", csb.PipeName);
            Assert.True(csb.OldGuids);
            Assert.True(csb.PersistSecurityInfo);
            Assert.False(csb.Pooling);
            Assert.Equal(1234u, csb.Port);
            Assert.Equal("db-server", csb.Server);
            Assert.False(csb.TreatTinyAsBoolean);
            Assert.Equal("ca.pem", csb.SslCa);
            Assert.Equal("client-cert.pem", csb.SslCert);
            Assert.Equal("client-key.pem", csb.SslKey);
            Assert.Equal(MySqlSslMode.VerifyCA, csb.SslMode);
            Assert.True(csb.UseAffectedRows);
            Assert.True(csb.UseCompression);
            Assert.Equal("username", csb.UserID);
        }
        public void ConstructWithEmptyString()
        {
            var csb = new MySqlConnectionStringBuilder("");

            Assert.Equal("", csb.ConnectionString);
        }
Пример #27
0
        public void CommitDoesNotTimeout()
        {
            const int requiredNumberOfRuns = 1;
            const int binarySize = 5000000;
            const int requiredNumberOfRowsPerRun = 100;

            Debug.WriteLine("Required Number Of Runs :" + requiredNumberOfRuns);
            Debug.WriteLine("Required Number Of Rows Per Run :" + requiredNumberOfRowsPerRun);

            suExecSQL("SET GLOBAL max_allowed_packet=64000000");

            MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

            using (MySqlConnection connection = new MySqlConnection(GetConnectionString(true)))
            {
                connection.Open();

                using (MySqlCommand command = new MySqlCommand())
                {
                    command.Connection = connection;
                    command.CommandType = CommandType.Text;
                    command.CommandText = "DROP TABLE IF EXISTS test_timeout;";
                    command.ExecuteNonQuery();

                    StringBuilder sqlCommand = new StringBuilder(512);

                    sqlCommand.Append("CREATE TABLE test_timeout (");
                    sqlCommand.Append("identity INT NOT NULL auto_increment, ");
                    sqlCommand.Append("a INT NOT NULL, ");
                    sqlCommand.Append("b INT NOT NULL, ");
                    sqlCommand.Append("c INT NOT NULL, ");
                    sqlCommand.Append("binary_data LONGBLOB NOT NULL, ");
                    sqlCommand.Append("PRIMARY KEY(identity), ");
                    sqlCommand.Append("KEY `abc` (`a`,`b`, `c`) ");
                    sqlCommand.Append(") ENGINE = INNODB");

                    command.CommandText = sqlCommand.ToString();
                    command.ExecuteNonQuery();
                }

                for (int numberOfRuns = 0; numberOfRuns < requiredNumberOfRuns; ++numberOfRuns)
                {
                    using (MySqlTransaction transaction = connection.BeginTransaction())
                    {
                        Stopwatch stopwatch = Stopwatch.StartNew();

                        using (MySqlCommand command = new MySqlCommand())
                        {
                            command.Connection = connection;
                            command.CommandText = "INSERT INTO test_timeout VALUES (?f1, ?f2, ?f3, ?f4, ?f5)";
                            command.Parameters.Add("?f1", MySqlDbType.Int32);
                            command.Parameters.Add("?f2", MySqlDbType.Int32);
                            command.Parameters.Add("?f3", MySqlDbType.Int32);
                            command.Parameters.Add("?f4", MySqlDbType.Int32);
                            command.Parameters.Add("?f5", MySqlDbType.LongBlob);
                            command.CommandTimeout = 0;
                            command.Prepare();

                            byte[] buffer;

                            using (MemoryStream stream = new MemoryStream())
                            {
                                using (BinaryWriter binary = new BinaryWriter(stream))
                                {
                                    int count = 0;

                                    while (stream.Position < binarySize)
                                    {
                                        binary.Write(++count);
                                    }
                                }

                                buffer = stream.ToArray();
                            }

                            for (int i = 0; i < requiredNumberOfRowsPerRun; ++i)
                            {
                                command.Parameters[1].Value = i;
                                command.Parameters[2].Value = i;
                                command.Parameters[3].Value = i;
                                command.Parameters[4].Value = buffer;
                                command.ExecuteNonQuery();
                            }
                        }

                        transaction.Commit();

                        Assert.IsNotNull(transaction);

                        stopwatch.Stop();

                        double seconds = stopwatch.Elapsed.TotalSeconds;
                        double recordsPerSecond = requiredNumberOfRowsPerRun / seconds;

                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("Truncate Result : Insert {0} Took {1:F4}; Per Second {2:F1} ",
                        requiredNumberOfRowsPerRun, seconds, recordsPerSecond);

                        Debug.WriteLine(sb.ToString());
                    }

                    using (MySqlCommand command = new MySqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "SELECT * FROM test_timeout";

                        Stopwatch stopwatch = Stopwatch.StartNew();
                        int count = 0;

                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            int previous = -1;

                            while (reader.Read())
                            {
                                int current = reader.GetInt32(0);
                                Assert.Greater(current, previous);
                                previous = current;

                                ++count;
                            }
                        }

                        stopwatch.Stop();

                        double seconds = stopwatch.Elapsed.TotalSeconds;
                        double recordsPerSecond = count / seconds;

                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("Test Result : Select {0} Took {1:F4}; Per Second {2:F1} ",
                        count, seconds, recordsPerSecond);

                        Debug.WriteLine(sb.ToString());
                    }

                    using (MySqlCommand command = new MySqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "TRUNCATE TABLE test_timeout";
                        command.ExecuteNonQuery();
                    }
                }

                MySqlConnection.ClearPool(connection);
            }
        }
Пример #28
0
 private void checkBox1_CheckedChanged(object sender, EventArgs e)
 {
     if (checkBox1.Checked)
     {
         lblParaQuien.Text = "Trabajador";
         try
         {
             MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
             builder.Server   = "31.170.166.58";
             builder.UserID   = "u215283317_pb";
             builder.Password = "******";
             builder.Database = "u215283317_pb";
             MySqlConnection conn = new MySqlConnection(builder.ToString());
             conn.Open();
             MySqlCommand cmd = conn.CreateCommand();
             cmd.CommandText = "SELECT * FROM trabajadores WHERE visible='si'";
             MySqlDataReader lector = cmd.ExecuteReader();
             while (lector.Read())
             {
                 cbClientes.Items.Add(lector["id"] + ", " + lector["nombre"]);
             }
             lector.Close();
             conn.Close();
         }
         catch (Exception ex)
         {
             this.Enabled = true;
             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             this.Close();
         }
     }
     else
     {
         lblParaQuien.Text = "Cliente";
         try
         {
             MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
             builder.Server   = "31.170.166.58";
             builder.UserID   = "u215283317_pb";
             builder.Password = "******";
             builder.Database = "u215283317_pb";
             MySqlConnection conn = new MySqlConnection(builder.ToString());
             conn.Open();
             MySqlCommand cmd = conn.CreateCommand();
             cmd.CommandText = "SELECT * FROM clientes WHERE visible='si'";
             MySqlDataReader lector = cmd.ExecuteReader();
             while (lector.Read())
             {
                 cbClientes.Items.Add(lector["id"] + ", " + lector["nombre"]);
             }
             lector.Close();
             conn.Close();
         }
         catch (Exception ex)
         {
             this.Enabled = true;
             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             this.Close();
         }
     }
 }
        public void ConstructWithNull()
        {
            var csb = new MySqlConnectionStringBuilder(default(string));

            Assert.Equal("", csb.ConnectionString);
        }
        public ConnectionSettings(MySqlConnectionStringBuilder csb)
        {
            ConnectionStringBuilder = csb;
            ConnectionString        = csb.ConnectionString;

            if (csb.ConnectionProtocol == MySqlConnectionProtocol.UnixSocket || (!Utility.IsWindows() && (csb.Server.StartsWith("/", StringComparison.Ordinal) || csb.Server.StartsWith("./", StringComparison.Ordinal))))
            {
                if (!File.Exists(csb.Server))
                {
                    throw new MySqlException("Cannot find Unix Socket at " + csb.Server);
                }
                ConnectionProtocol = MySqlConnectionProtocol.UnixSocket;
                UnixSocket         = Path.GetFullPath(csb.Server);
            }
            else if (csb.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe)
            {
                ConnectionProtocol = MySqlConnectionProtocol.NamedPipe;
                HostNames          = (csb.Server == "." || string.Equals(csb.Server, "localhost", StringComparison.OrdinalIgnoreCase)) ? s_localhostPipeServer : new[] { csb.Server };
                PipeName           = csb.PipeName;
            }
            else if (csb.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
            {
                throw new NotSupportedException("Shared Memory connections are not supported");
            }
            else
            {
                ConnectionProtocol = MySqlConnectionProtocol.Sockets;
                HostNames          = csb.Server.Split(',');
                LoadBalance        = csb.LoadBalance;
                Port = (int)csb.Port;
            }

            UserID   = csb.UserID;
            Password = csb.Password;
            Database = csb.Database;

            // SSL/TLS Options
            SslMode                  = csb.SslMode;
            CertificateFile          = csb.CertificateFile;
            CertificatePassword      = csb.CertificatePassword;
            CACertificateFile        = csb.CACertificateFile;
            CertificateStoreLocation = csb.CertificateStoreLocation;
            CertificateThumbprint    = csb.CertificateThumbprint;

            // Connection Pooling Options
            Pooling                = csb.Pooling;
            ConnectionLifeTime     = Math.Min(csb.ConnectionLifeTime, uint.MaxValue / 1000) * 1000;
            ConnectionReset        = csb.ConnectionReset;
            ConnectionIdlePingTime = Math.Min(csb.ConnectionIdlePingTime, uint.MaxValue / 1000) * 1000;
            ConnectionIdleTimeout  = (int)csb.ConnectionIdleTimeout;
            if (csb.MinimumPoolSize > csb.MaximumPoolSize)
            {
                throw new MySqlException("MaximumPoolSize must be greater than or equal to MinimumPoolSize");
            }
            MinimumPoolSize = (int)csb.MinimumPoolSize;
            MaximumPoolSize = (int)csb.MaximumPoolSize;

            // Other Options
            AllowPublicKeyRetrieval = csb.AllowPublicKeyRetrieval;
            AllowUserVariables      = csb.AllowUserVariables;
            AllowZeroDateTime       = csb.AllowZeroDateTime;
            ApplicationName         = csb.ApplicationName;
            AutoEnlist               = csb.AutoEnlist;
            ConnectionTimeout        = (int)csb.ConnectionTimeout;
            ConvertZeroDateTime      = csb.ConvertZeroDateTime;
            DateTimeKind             = (DateTimeKind)csb.DateTimeKind;
            DefaultCommandTimeout    = (int)csb.DefaultCommandTimeout;
            ForceSynchronous         = csb.ForceSynchronous;
            IgnoreCommandTransaction = csb.IgnoreCommandTransaction;
            IgnorePrepare            = csb.IgnorePrepare;
            InteractiveSession       = csb.InteractiveSession;
            GuidFormat               = GetEffectiveGuidFormat(csb.GuidFormat, csb.OldGuids);
            Keepalive              = csb.Keepalive;
            PersistSecurityInfo    = csb.PersistSecurityInfo;
            ServerRsaPublicKeyFile = csb.ServerRsaPublicKeyFile;
            ServerSPN              = csb.ServerSPN;
            TreatTinyAsBoolean     = csb.TreatTinyAsBoolean;
            UseAffectedRows        = csb.UseAffectedRows;
            UseCompression         = csb.UseCompression;
            UseXaTransactions      = csb.UseXaTransactions;
        }
 public void EncryptKeyword()
 {
     string connStr = "database=test;uid=root;server=localhost;encrypt=yes";
     MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr);
 }
Пример #32
0
        public void Insertarpoliza(FormSALIDAS formpolizas, string titulos)//insertar nueva orden
        {
            MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder();

            sb.Server   = "secure199.inmotionhosting.com";
            sb.UserID   = "abdsto5_felipe";
            sb.Password = "******";
            sb.Database = "abdsto5_cotizaciones";


            //PRUEBAS EN LOCALHOST

            /*
             * sb.Server = "localhost";
             * sb.UserID = "felipe";
             * sb.Password = "******";
             * sb.Database = "ejemplo";
             */
            bdMysql = new DataBase();
            bdMysql.DataBaseProvider = TypeOfDataBase.MySqlServer;
            bdMysql.ConnectionString = sb.ToString();
            bdMysql.CreateConnection();
            DbObject.DefaultDataBaseObject = bdMysql;


            ID = 0;
actualizarfolio:
            try
            {
                folio  = this.NextNumber("folio");
                fecha  = DateTime.Now.Date;
                titulo = titulos;
                if (formpolizas.REMISION.Text != "")
                {
                    titulo = titulo + "Remision: " + formpolizas.REMISION.Text + "\n";
                }
                if (formpolizas.COTIZACION.Text != "")
                {
                    titulo = titulo + "Cotizacion: " + formpolizas.COTIZACION.Text + "\n";
                }
                if (formpolizas.checkBoxPorProyecto.Checked == true)
                {
                    titulo = titulo + "Proyecto: " + formpolizas.comboBoxProyecto.Text + " " + formpolizas.textBoxProyectoId.Text + "\n";
                }
                moneda         = "USD";
                subtotal       = Math.Round(formpolizas.sumatoria, 2);
                iva            = 0;
                ingreso        = 0;
                egreso         = Math.Round(formpolizas.sumatoria, 2);
                fechaoperacion = DateTime.Now.Date;
                factura        = formpolizas.FACTURA.Text;
                pocliente      = formpolizas.txtpo.Text;
                remision       = formpolizas.REMISION.Text;
                if (remision == "")
                {
                    remision = formpolizas.COTIZACION.Text;
                }
                origen    = "ALMACEN";
                suborigen = "N/A";
                if (formpolizas.checkBoxPorProyecto.Checked == true)
                {
                    destino = "PREFACTURA PROYECTOS";
                }
                else
                {
                    destino = "PREFACTURA PRODUCTOS";
                }
                subdestino       = formpolizas.comboBoxClientes.Text;
                notas            = "SALIDA AUTOMATICA DE ALMACEN";
                tipo             = "EGRESO";
                estatus          = 1;
                adjunto1         = "";
                saldo            = 0;
                estatus2         = 1;
                numero           = "";
                saldoglobal      = 0;
                proveedor        = "";
                porcentajemargen = 0;
                programado       = "";
                if (estatus == 1 && origen != "PROVEEDORES")
                {
                    programado = "pagado";
                }
                if (origen == "CAJA" || origen == "PROVEEDORES" || origen == "BRANNSTORE" || origen == "PRE IMPORTACION")
                {
                    programado = "";
                }
                if (estatus == 2)
                {
                    programado = "pagado";
                }
                deducible     = "NO";
                tipocambio    = Convert.ToDouble(formpolizas.textBoxTipoCambio.Text);
                retension     = 0;
                retension_isr = 0;
                saldo2        = 0;
                saldo3        = 0;
                saldo4        = 0;
                if (formpolizas.comboVendedor.Text == "Felipe Ortiz" || formpolizas.comboVendedor.Text == "Oficina" || formpolizas.comboVendedor.Text == "Antonio Viera")
                {
                    idnegocio = 1;
                }
                else if (formpolizas.comboVendedor.Text == "Jesus ortiz")
                {
                    idnegocio = 19;
                }
                else if (formpolizas.comboVendedor.Text == "Samuel" || formpolizas.comboVendedor.Text == "Taller")
                {
                    idnegocio = 18;
                }
                else
                {
                    idnegocio = 3;
                }
                idproyecto = formpolizas.idproyectos;

                pocliente = formpolizas.txtpo.Text;
                if (formpolizas.checkBoxPorProyecto.Checked == true)
                {
                    prefactura = Convert.ToInt32(this.factura(idproyecto.ToString()));
                }
                else
                {
                    idproyecto = 0;
                    if (formpolizas.txtpo.Text != "" && formpolizas.txtpo.Text != "0")
                    {
                        prefactura = Convert.ToInt32(this.facturapoliza(pocliente));
                    }
                }
                this.Insert();
                if (this.Error != "")
                {
                    goto actualizarfolio;
                }
                else
                {
                    formpolizas.OSAGralSeleccionada.actualizarosa("idpoliza", folio.ToString(), "Id=" + formpolizas.OSAGralSeleccionada.Id.ToString());
                }
            }
            catch
            {
                goto actualizarfolio;
            }
        }
 public void SettingInvalidKeyThrowsArgumentException()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder();
     s["foo keyword"] = "foo";
 }
Пример #34
0
 public void SetUpFixture()
 {
     _connectionStringBuilder = new MySqlConnectionStringBuilder();
     _connectionStringBuilder.ConnectionString = "Server = testserver; Database = test; User Id = root; Password = Password1";
     _connection = _connectionStringBuilder.Open();
 }
        public void EnumInvalidOperation()
        {
            var csb = new MySqlConnectionStringBuilder("ssl mode=invalid;");

            Assert.Throws <InvalidOperationException>(() => csb.SslMode);
        }
Пример #36
0
 internal virtual void AdjustConnectionSettings(MySqlConnectionStringBuilder settings)
 {
 }
Пример #37
0
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            string ids      = textBoxX1.Text;
            string lname    = textBoxX2.Text;
            string fname    = textBoxX3.Text;
            string age      = textBoxX4.Text;
            string user     = textBoxX6.Text;
            string pass     = textBoxX5.Text;
            string userlevs = "Admin";

            if (lname == "" || fname == "" || age == "" || user == "" || pass == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Empty Fields Detected");
                return;
            }
            MySqlConnectionStringBuilder gsdb = new MySqlConnectionStringBuilder();

            gsdb.Server   = "localhost";
            gsdb.UserID   = "root";
            gsdb.Password = "";
            gsdb.Database = "GradingSystem";
            MySqlConnection connection = new MySqlConnection(gsdb.ToString());

            connection.Open();
            string       newuser_sql = "INSERT INTO admins (adminID,admin_lname,admin_fname,admin_age) VALUES (@ids, @lname, @fname,@age)";
            MySqlCommand newuser     = new MySqlCommand(newuser_sql, connection);

            newuser.CommandText = newuser_sql;
            newuser.Parameters.AddWithValue("@ids", ids);
            newuser.Parameters.AddWithValue("@lname", lname);
            newuser.Parameters.AddWithValue("@fname", fname);
            newuser.Parameters.AddWithValue("@age", age);
            newuser.ExecuteNonQuery();
            {
            }
            DevExpress.XtraEditors.XtraMessageBox.Show("New Admin Registered");

            string query1 = "INSERT INTO Account(adminID,AccountName,userlevel,Username,Passwords) values ('" + ids + "','" + lname + ',' + fname + "','" + userlevs + "','" + user + "','" + pass + "');";

            MySqlCommand newquery = new MySqlCommand(query1, connection);

            getName();
            newquery.ExecuteNonQuery();


            textBoxX2.Text = "";
            textBoxX3.Text = "";
            textBoxX4.Text = "";
            textBoxX5.Text = "";
            textBoxX6.Text = "";
            connection.Close();
            connection.Open();
            string       activity     = "Add Admmin";
            string       newuser_sql2 = "INSERT INTO acty (Actname,namex,userlevel,IdAct) VALUES (@act, @namc, @levels,@act1)";
            MySqlCommand newuser1     = new MySqlCommand(newuser_sql2, connection);

            newuser1.CommandText = newuser_sql2;
            newuser1.Parameters.AddWithValue("@act", activity);
            newuser1.Parameters.AddWithValue("@namc", label7.Text);
            newuser1.Parameters.AddWithValue("@levels", label8.Text);
            newuser1.Parameters.AddWithValue("@act1", textBoxX2.Text);
            newuser1.ExecuteNonQuery();
            {
            }
            account_tbl();
            connection.Close();
        }
Пример #38
0
        private static Stream GetNamedPipeStream(MySqlConnectionStringBuilder settings)
        {
            Stream stream = NamedPipeStream.Create(settings.PipeName, settings.Server, settings.ConnectionTimeout);

            return(stream);
        }
Пример #39
0
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

            builder.Server   = SERVER;
            builder.Database = DATABASE;
            builder.UserID   = UID;
            builder.Password = PASSWORD;

            MySqlDataAdapter adapter;
            DataTable        table = new DataTable();

            String connString = builder.ToString();

            dbConn = new MySqlConnection(connString);

            try
            {
                bool loginPetugas = false;
                bool loginAnggota = false;

                dbConn.Open();
                MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM daftarloginlogoutpetugas WHERE username = '******' && password='******'", dbConn);
                DataTable        dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count <= 0)
                {
                    loginPetugas = false;
                }
                else
                {
                    loginPetugas = true;
                }
                dbConn.Close();

                dbConn.Open();
                da = new MySqlDataAdapter("SELECT * FROM daftarloginlogoutanggota WHERE username = '******' && password='******'", dbConn);
                dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count <= 0)
                {
                    loginAnggota = false;
                }
                else
                {
                    loginAnggota = true;
                }
                dbConn.Close();

                if (loginPetugas == true)
                {
                    loginPetugas = false;
                    Form2 frm2 = new Form2(this);
                    frm2.Show();
                }
                else if (loginAnggota == true)
                {
                    loginAnggota = false;
                    Form3 frm3 = new Form3(this);
                    frm3.Show();
                }
                else
                {
                    MessageBox.Show("Password atau Username salah!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Koneksi Error");
            }
        }
Пример #40
0
        private static Stream GetTcpStream(MySqlConnectionStringBuilder settings)
        {
            MyNetworkStream s = MyNetworkStream.CreateStream(settings, false);

            return(s);
        }
Пример #41
0
 internal void Serialize(MySqlPacket packet, bool binary, MySqlConnectionStringBuilder settings)
 {
     if (!binary && (paramValue == null || paramValue == DBNull.Value))
         packet.WriteStringNoNull("NULL");
     else
     {
         if (ValueObject.MySqlDbType == MySqlDbType.Guid)
         {
             MySqlGuid g = (MySqlGuid)ValueObject;
             g.OldGuids = settings.OldGuids;
             ValueObject = g;
         }
         if (ValueObject.MySqlDbType == MySqlDbType.Geometry)
         {
             MySqlGeometry v = (MySqlGeometry)ValueObject;
             if (v.IsNull && Value != null)
             {
                 MySqlGeometry.TryParse(Value.ToString(), out v);
             }
             ValueObject = v;
         }
         ValueObject.WriteValue(packet, binary, paramValue, Size);
     }
 }
 internal protected virtual ReplicationServer GetServer(bool isMaster, MySqlConnectionStringBuilder settings)
 {
   return GetServer(isMaster);
 }
 public override void AdjustConnectionSettings(MySqlConnectionStringBuilder settings)
 {
     settings.ConnectionProtocol      = MySqlConnectionProtocol.SharedMemory;
     settings.SslMode                 = MySqlSslMode.None;
     settings.AllowPublicKeyRetrieval = true;
 }
Пример #44
0
 /// <include file='docs/MySqlConnection.xml' path='docs/DefaultCtor/*'/>
 public MySqlConnection()
 {
     //TODO: add event data to StateChange docs
     Settings = new MySqlConnectionStringBuilder();
     database = String.Empty;
 }
Пример #45
0
        public static ConnectionPool GetPool(string connectionString)
        {
            // check single-entry MRU cache for this exact connection string; most applications have just one
            // connection string and will get a cache hit here
            var cache = s_mruCache;

            if (cache?.ConnectionString == connectionString)
            {
                return(cache.Pool);
            }

            // check if pool has already been created for this exact connection string
            if (s_pools.TryGetValue(connectionString, out var pool))
            {
                s_mruCache = new ConnectionStringPool(connectionString, pool);
                return(pool);
            }

            // parse connection string and check for 'Pooling' setting; return 'null' if pooling is disabled
            var connectionStringBuilder = new MySqlConnectionStringBuilder(connectionString);

            if (!connectionStringBuilder.Pooling)
            {
                s_pools.GetOrAdd(connectionString, default(ConnectionPool));
                s_mruCache = new ConnectionStringPool(connectionString, null);
                return(null);
            }

            // check for pool using normalized form of connection string
            var normalizedConnectionString = connectionStringBuilder.ConnectionString;

            if (normalizedConnectionString != connectionString && s_pools.TryGetValue(normalizedConnectionString, out pool))
            {
                // try to set the pool for the connection string to the canonical pool; if someone else
                // beats us to it, just use the existing value
                pool       = s_pools.GetOrAdd(connectionString, pool);
                s_mruCache = new ConnectionStringPool(connectionString, pool);
                return(pool);
            }

            // create a new pool and attempt to insert it; if someone else beats us to it, just use their value
            var connectionSettings = new ConnectionSettings(connectionStringBuilder);
            var newPool            = new ConnectionPool(connectionSettings);

            pool = s_pools.GetOrAdd(normalizedConnectionString, newPool);

            if (pool == newPool)
            {
                s_mruCache = new ConnectionStringPool(connectionString, pool);
                pool.StartReaperTask();

                // if we won the race to create the new pool, also store it under the original connection string
                if (connectionString != normalizedConnectionString)
                {
                    s_pools.GetOrAdd(connectionString, pool);
                }
            }
            else if (pool != newPool && Log.IsInfoEnabled())
            {
                Log.Info("Pool{0} was created but will not be used (due to race)", newPool.m_logArguments);
            }

            return(pool);
        }
        public void Defaults()
        {
            var csb = new MySqlConnectionStringBuilder();

            Assert.False(csb.AllowLoadLocalInfile);
            Assert.False(csb.AllowPublicKeyRetrieval);
            Assert.False(csb.AllowUserVariables);
            Assert.False(csb.AllowZeroDateTime);
            Assert.True(csb.AutoEnlist);
            Assert.Null(csb.CertificateFile);
            Assert.Null(csb.CertificatePassword);
            Assert.Equal(MySqlCertificateStoreLocation.None, csb.CertificateStoreLocation);
            Assert.Null(csb.CertificateThumbprint);
            Assert.Equal("", csb.CharacterSet);
            Assert.Equal(0u, csb.ConnectionLifeTime);
            Assert.Equal(MySqlConnectionProtocol.Sockets, csb.ConnectionProtocol);
#if BASELINE
            Assert.False(csb.ConnectionReset);
#else
            Assert.True(csb.ConnectionReset);
#endif
            Assert.Equal(15u, csb.ConnectionTimeout);
            Assert.False(csb.ConvertZeroDateTime);
#if !BASELINE
            Assert.Equal(MySqlDateTimeKind.Unspecified, csb.DateTimeKind);
#endif
            Assert.Equal("", csb.Database);
            Assert.Equal(30u, csb.DefaultCommandTimeout);
#if !BASELINE
            Assert.Null(csb.ApplicationName);
            Assert.Equal(0u, csb.ConnectionIdlePingTime);
            Assert.Equal(180u, csb.ConnectionIdleTimeout);
            Assert.False(csb.ForceSynchronous);
            Assert.Equal(MySqlGuidFormat.Default, csb.GuidFormat);
            Assert.False(csb.IgnoreCommandTransaction);
            Assert.Equal(MySqlLoadBalance.RoundRobin, csb.LoadBalance);
#endif
            Assert.True(csb.IgnorePrepare);
            Assert.False(csb.InteractiveSession);
            Assert.Equal(0u, csb.Keepalive);
            Assert.Equal(100u, csb.MaximumPoolSize);
            Assert.Equal(0u, csb.MinimumPoolSize);
            Assert.Equal("", csb.Password);
            Assert.Equal("MYSQL", csb.PipeName);
#if !BASELINE
            Assert.False(csb.NoBackslashEscapes);
#endif
            Assert.False(csb.OldGuids);
            Assert.False(csb.PersistSecurityInfo);
            Assert.True(csb.Pooling);
            Assert.Equal(3306u, csb.Port);
            Assert.Equal("", csb.Server);
#if !BASELINE
            Assert.Null(csb.ServerRsaPublicKeyFile);
            Assert.Null(csb.ServerSPN);
#endif
            Assert.Null(csb.SslCa);
            Assert.Null(csb.SslCert);
            Assert.Null(csb.SslKey);
            Assert.Equal(MySqlSslMode.Preferred, csb.SslMode);
            Assert.Null(csb.TlsVersion);
            Assert.True(csb.TreatTinyAsBoolean);
            Assert.False(csb.UseCompression);
            Assert.Equal("", csb.UserID);
            Assert.False(csb.UseAffectedRows);
#if !BASELINE
            Assert.True(csb.UseXaTransactions);
#endif
        }
        public void TreatTinyAsBool()
        {
            if (version < new Version(4, 1)) return;
            execSQL("CREATE TABLE Test2(i TINYINT(1))");
            execSQL("INSERT INTO Test2 VALUES(1)");
            execSQL("INSERT INTO Test2 VALUES(0)");
            execSQL("INSERT INTO Test2 VALUES(2)");
            MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(conn.ConnectionString);
            Assert.IsTrue(builder.TreatTinyAsBoolean);

            MySqlCommand cmd = new MySqlCommand("SELECT * from Test2", conn);
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                bool b;
                Assert.IsTrue(reader.Read());
                b = (bool)reader.GetValue(0);
                Assert.IsTrue(b);
                Assert.IsTrue(reader.Read());
                b = (bool)reader.GetValue(0);
                Assert.IsFalse(b);
                Assert.IsTrue(reader.Read());
                b = (bool)reader.GetValue(0);
                Assert.IsTrue(b);
            }
        }
Пример #48
0
 public MySQLProvider(MySqlConnectionStringBuilder connectionStringBuilder, IRunOperationService runOperationService, IInteractiveQuestion question)
     : this(connectionStringBuilder.GetConnectionString(true), runOperationService, question)
 {
 }
Пример #49
0
        public void CancelQuery(int timeout)
        {
            MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder(
              Settings.ConnectionString);
            cb.Pooling = false;
            cb.AutoEnlist = false;
            cb.ConnectionTimeout = (uint)timeout;

            using (MySqlConnection c = new MySqlConnection(cb.ConnectionString))
            {
                c.isKillQueryConnection = true;
                c.Open();
                string commandText = "KILL QUERY " + ServerThread;
                MySqlCommand cmd = new MySqlCommand(commandText, c);
                cmd.CommandTimeout = timeout;
                cmd.ExecuteNonQuery();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="eventCache"></param>
        /// <param name="source"></param>
        /// <param name="eventType"></param>
        /// <param name="id"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id,
                                        string format, params object[] args)
        {
            switch ((MySqlTraceEventType)id)
            {
            case MySqlTraceEventType.ConnectionOpened:
                var driverId = (long)args[0];
                var connStr  = args[1].ToString();
                _dbConn[driverId] = new MySqlConnectionStringBuilder(connStr);
                break;

            case MySqlTraceEventType.ConnectionClosed:
                //TODO
                break;

            case MySqlTraceEventType.QueryOpened:
                BeforeExecuteCommand(GetCommand(args[0], args[2]));
                break;

            case MySqlTraceEventType.ResultOpened:
                //TODO
                break;

            case MySqlTraceEventType.ResultClosed:
                //TODO
                break;

            case MySqlTraceEventType.QueryClosed:
                AfterExecuteCommand();
                break;

            case MySqlTraceEventType.StatementPrepared:
                //TODO
                break;

            case MySqlTraceEventType.StatementExecuted:
                //TODO
                break;

            case MySqlTraceEventType.StatementClosed:
                //TODO
                break;

            case MySqlTraceEventType.NonQuery:
                //TODO
                break;

            case MySqlTraceEventType.UsageAdvisorWarning:
                //TODO
                break;

            case MySqlTraceEventType.Warning:
                //TODO
                break;

            case MySqlTraceEventType.Error:
                ErrorExecuteCommand(GetMySqlErrorException(args[1], args[2]));
                break;

            case MySqlTraceEventType.QueryNormalized:
                //TODO
                break;
            }
        }
 public void UseProcedureBodiesSettingCheckParameters()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder("server=localhost;use procedure bodies=false");
     Assert.IsFalse(s.CheckParameters);
 }
Пример #52
0
 public static void SetConnectionString(MySqlConnectionStringBuilder connectionString)
 {
     ConnectionString = connectionString.ConnectionString;
 }
 public void ContainsKey()
 {
     MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder();
     s["database"] = "test";
     Assert.IsTrue(s.ContainsKey("initial catalog"));
     s["server"] = "myserver";
     Assert.IsTrue(s.ContainsKey("server"));
     Assert.IsTrue(s.ContainsKey("host"));
     Assert.IsFalse(s.ContainsKey("badkey"));
 }
Пример #54
0
        internal static void Initialize()
        {
            Console.Clear();
            CyberEnvironment.ServerStarted = DateTime.Now;
            Console.SetWindowSize(120, 40);
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
            Console.WriteLine(@"                              ____ _   _ ___  ____ ____    ____ _  _ _  _ _    ____ ___ ____ ____ ");
            Console.WriteLine(@"                              |     \_/  |__] |___ |__/    |___ |\/| |  | |    |__|  |  |  | |__/ ");
            Console.WriteLine(@"                              |___   |   |__] |___ |  \    |___ |  | |__| |___ |  |  |  |__| |  \ ");
            Console.WriteLine();
            Console.WriteLine("                                                Cyber Emulator - Version: " + PrettyBuild);
            Console.WriteLine("                                         based on Plus, developed by Kessiler Rodrigues.");
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("                                                 " + PrettyRelease);
            Console.Title = "Cyber Emulator | Loading data [...]";
            CyberEnvironment.DefaultEncoding = Encoding.Default;
            Console.WriteLine("");

            CyberEnvironment.cultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
            TextHandling.replaceDecimal();
            try
            {
                CyberEnvironment.Configuration = new ConfigurationData(Path.Combine(Application.StartupPath, "config.ini"), false);


                MySqlConnectionStringBuilder mySqlConnectionStringBuilder = new MySqlConnectionStringBuilder();
                mySqlConnectionStringBuilder.Server                = (CyberEnvironment.GetConfig().data["db.hostname"]);
                mySqlConnectionStringBuilder.Port                  = (uint.Parse(CyberEnvironment.GetConfig().data["db.port"]));
                mySqlConnectionStringBuilder.UserID                = (CyberEnvironment.GetConfig().data["db.username"]);
                mySqlConnectionStringBuilder.Password              = (CyberEnvironment.GetConfig().data["db.password"]);
                mySqlConnectionStringBuilder.Database              = (CyberEnvironment.GetConfig().data["db.name"]);
                mySqlConnectionStringBuilder.MinimumPoolSize       = (uint.Parse(CyberEnvironment.GetConfig().data["db.pool.minsize"]));
                mySqlConnectionStringBuilder.MaximumPoolSize       = (uint.Parse(CyberEnvironment.GetConfig().data["db.pool.maxsize"]));
                mySqlConnectionStringBuilder.Pooling               = (true);
                mySqlConnectionStringBuilder.AllowZeroDateTime     = (true);
                mySqlConnectionStringBuilder.ConvertZeroDateTime   = (true);
                mySqlConnectionStringBuilder.DefaultCommandTimeout = (300u);
                mySqlConnectionStringBuilder.ConnectionTimeout     = (10u);
                CyberEnvironment.manager = new DatabaseManager(mySqlConnectionStringBuilder.ToString());

                using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    ConfigData = new ConfigData(queryreactor);
                    PetLocale.Init(queryreactor);
                    OfflineMessages = new Dictionary <uint, List <OfflineMessage> >();
                    OfflineMessage.InitOfflineMessages(queryreactor);
                    GiftWrappers = new GiftWrappers(queryreactor);
                }

                FriendRequestLimit = (uint)int.Parse(CyberEnvironment.GetConfig().data["client.maxrequests"]);
                if (ExtraSettings.RunExtraSettings())
                {
                    Logging.WriteLine("Loaded an extra settings file.");
                }

                Game = new Game(int.Parse(GetConfig().data["game.tcp.conlimit"]));
                Game.start();

                ConnectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");

                HabboCrypto.Initialize(new RsaKeyHolder());
                CyberEnvironment.ConnectionManager.init();
                CyberEnvironment.ConnectionManager.Start();
                StaticClientMessageHandler.Initialize();

                string[] allowedIps = GetConfig().data["mus.tcp.allowedaddr"].Split(';');
                MusSystem = new MusSocket(GetConfig().data["mus.tcp.bindip"], int.Parse(GetConfig().data["mus.tcp.port"]), allowedIps, 0);


                if (Configuration.data.ContainsKey("StaffAlert.MinRank"))
                {
                    StaffAlertMinRank = uint.Parse(CyberEnvironment.GetConfig().data["StaffAlert.MinRank"]);
                }
                if (Configuration.data.ContainsKey("SeparatedTasksInMainLoops.enabled") && Configuration.data["SeparatedTasksInMainLoops.enabled"] == "true")
                {
                    SeparatedTasksInMainLoops = true;
                }
                if (Configuration.data.ContainsKey("SeparatedTasksInGameClientManager.enabled") && Configuration.data["SeparatedTasksInGameClientManager.enabled"] == "true")
                {
                    SeparatedTasksInGameClientManager = true;
                }
                Logging.WriteLine("Game was succesfully loaded.");
                isLive = true;
            }
            catch (KeyNotFoundException ex)
            {
                Logging.WriteLine("Something is missing in your configuration", ConsoleColor.Red);
                Logging.WriteLine(ex.ToString(), ConsoleColor.Yellow);
                Logging.WriteLine("Please type a key to shut down ...", ConsoleColor.Gray);
                Console.ReadKey(true);
                CyberEnvironment.Destroy();
            }
            catch (InvalidOperationException ex1)
            {
                Logging.WriteLine("Something wrong happened: " + ex1.Message, ConsoleColor.Red);
                Logging.WriteLine(ex1.ToString(), ConsoleColor.Yellow);
                Logging.WriteLine("Please type a key to shut down...", ConsoleColor.Gray);
                Console.ReadKey(true);
                CyberEnvironment.Destroy();
            }
            catch (Exception ex2)
            {
                Logging.WriteLine("An exception got caught: " + ex2.Message, ConsoleColor.Red);
                Logging.WriteLine("Type a key to know more about the error", ConsoleColor.Gray);
                Console.ReadKey();
                Logging.WriteLine(ex2.ToString(), ConsoleColor.Yellow);
                Logging.WriteLine("Please type a ket to shut down...", ConsoleColor.Gray);
                Console.ReadKey();
                Environment.Exit(1);
            }
        }
Пример #55
0
 protected internal virtual ReplicationServer GetServer(bool isMaster, MySqlConnectionStringBuilder settings)
 {
     return(this.GetServer(isMaster));
 }
Пример #56
0
        public static void RunCreation(CreationScript script, string server, string dbname, string login, string password)
        {
            if (script == null)
            {
                script = Scripts.First();
            }

            string connStr, host;
            uint   port = 3306;

            string[] uriSplit = server.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);

            host = uriSplit [0];
            if (uriSplit.Length > 1)
            {
                uint.TryParse(uriSplit [1], out port);
            }

            var conStrBuilder = new MySqlConnectionStringBuilder();

            conStrBuilder.Server   = host;
            conStrBuilder.Port     = port;
            conStrBuilder.UserID   = login;
            conStrBuilder.Password = password;

            connStr = conStrBuilder.GetConnectionString(true);

            var connectionDB = new MySqlConnection(connStr);

            try {
                logger.Info("Connecting to MySQL...");

                connectionDB.Open();
            } catch (MySqlException ex) {
                logger.Info("Строка соединения: {0}", connStr);
                logger.Error(ex, "Ошибка подключения к серверу.");
                if (ex.Number == 1045 || ex.Number == 0)
                {
                    MessageDialogWorks.RunErrorDialog("Доступ запрещен.\nПроверьте логин и пароль.");
                }
                else if (ex.Number == 1042)
                {
                    MessageDialogWorks.RunErrorDialog("Не удалось подключиться к серверу БД.");
                }
                else
                {
                    MessageDialogWorks.RunErrorDialog("Ошибка соединения с базой данных.");
                }

                connectionDB.Close();
                return;
            }

            logger.Info("Проверяем существует ли уже база.");

            var  sql          = "SHOW DATABASES;";
            var  cmd          = new MySqlCommand(sql, connectionDB);
            bool needDropBase = false;

            using (var rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    if (rdr [0].ToString() == dbname)
                    {
                        if (MessageDialogWorks.RunQuestionDialog("База с именем `{0}` уже существует на сервере. Удалить существующую базу перед соданием новой?", dbname))
                        {
                            needDropBase = true;
                            break;
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }

            logger.Info("Создаем новую базу.");
            progressDlg = new CreatorProgress();
            progressDlg.OperationText = "Получаем скрипт создания базы";
            progressDlg.Show();

            string sqlScript;

            using (Stream stream = System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream(script.Resource))
            {
                if (stream == null)
                {
                    throw new InvalidOperationException(String.Format("Ресурс {0} со скриптом не найден.", script.Resource));
                }
                StreamReader reader = new StreamReader(stream);
                sqlScript = reader.ReadToEnd();
            }

            int predictedCount = Regex.Matches(sqlScript, ";").Count;

            logger.Debug("Предполагаем наличие {0} команд в скрипте.", predictedCount);
            progressDlg.OperationText      = String.Format("Создаем базу <{0}>", dbname);
            progressDlg.OperationPartCount = predictedCount + (needDropBase ? 2 : 1);
            progressDlg.OperationCurPart   = 0;

            if (needDropBase)
            {
                logger.Info("Удаляем существующую базу {0}.", dbname);
                progressDlg.OperationText = String.Format("Удаляем существующую базу {0}", dbname);
                cmd.CommandText           = String.Format("DROP DATABASE `{0}`", dbname);
                cmd.ExecuteNonQuery();
                progressDlg.OperationCurPart++;
            }

            cmd.CommandText = String.Format("CREATE SCHEMA `{0}` DEFAULT CHARACTER SET utf8 ;", dbname);
            cmd.ExecuteNonQuery();
            cmd.CommandText = String.Format("USE `{0}` ;", dbname);
            cmd.ExecuteNonQuery();

            progressDlg.OperationText = String.Format("Создаем таблицы в <{0}>", dbname);
            progressDlg.OperationCurPart++;

            var myscript = new MySqlScript(connectionDB, sqlScript);

            myscript.StatementExecuted += Myscript_StatementExecuted;;
            var commands = myscript.Execute();

            logger.Debug("Выполнено {0} SQL-команд.", commands);

            progressDlg.Destroy();
            progressDlg = null;

            MessageDialogWorks.RunInfoDialog("Создание базы успешно завершено.\nЗайдите в программу под администратором для добавления пользователей.");
        }
Пример #57
0
 public MySqlDatabaseHelper(MySqlConnectionStringBuilder connectionBuilder)
 {
     _connection        = new MySqlConnection(connectionBuilder.ConnectionString);
     _disposeConnection = true;
 }
 public static void ClearPool(MySqlConnectionStringBuilder settings)
 {
   Debug.Assert(settings != null);
   string text;
   try
   {
     text = GetKey(settings);
   }
   catch (MySqlException)
   {
     // Cannot retrieve windows identity for IntegratedSecurity=true
     // This can be ignored.
     return;
   }
   ClearPoolByText(text);
 }
Пример #59
0
 public TracingDriver(MySqlConnectionStringBuilder settings)
   : base(settings)
 {
   driverId = Interlocked.Increment(ref driverCounter);
 }
 internal override void AdjustConnectionSettings(MySqlConnectionStringBuilder settings)
 {
     settings.UseCompression = true;
 }