/// <summary>
        /// Sets the current database for the this connection
        /// </summary>
        /// <param name="dbName"></param>
        public void SetDatabase(string dbName)
        {
            byte[] dbNameBytes = Encoding.GetBytes(dbName);

            packet.Clear();
            packet.WriteByte((byte)DBCmd.INIT_DB);
            packet.Write(dbNameBytes);
            ExecutePacket(packet);

            ReadOk(true);
        }
        /// <summary>
        /// Perform an authentication against a 4.1.1 server
        /// <param name="reset">
        /// True, if this function is called as part of CHANGE_USER request
        /// (connection reset)
        /// False, for first-time logon
        /// </param>
        /// </summary>
        private void AuthenticateNew(bool reset)
        {
            if ((connectionFlags & ClientFlags.SECURE_CONNECTION) == 0)
            {
                AuthenticateOld();
            }

            packet.Write(Crypt.Get411Password(Settings.Password, encryptionSeed));
            if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null)
            {
                packet.WriteString(Settings.Database);
            }
            else
            {
                packet.WriteString("");                 // Add a null termination to the string.
            }
            if (Settings.IntegratedSecurity)
            {
                // Append authentication method after the database name in the
                // handshake authentication packet.If we're sending CHANGE_USER
                // also write charset number after database name prior to plugin name
                if (reset)
                {
                    packet.WriteInteger(8, 2);                     // Charset number
                }
                packet.WriteString(AuthenticationWindowsPlugin);
                stream.SendPacket(packet);
                AuthenticateSSPI();
                return;
            }
            else
            {
                stream.SendPacket(packet);
            }

            // this result means the server wants us to send the password using
            // old encryption
            packet = stream.ReadPacket();
            if (packet.IsLastPacket)
            {
                packet.Clear();
                packet.WriteString(Crypt.EncryptPassword(
                                       Settings.Password, encryptionSeed.Substring(0, 8), true));
                stream.SendPacket(packet);
                ReadOk(true);
            }
            ReadOk(false);
        }
        /// <summary>
        /// Perform an authentication against a 4.1.1 server
        /// <param name="reset">
        /// True, if this function is called as part of CHANGE_USER request
        /// (connection reset)
        /// False, for first-time logon
        /// </param>
        /// </summary>
        private void AuthenticateNew(bool reset)
        {
            if ((connectionFlags & ClientFlags.SECURE_CONNECTION) == 0)
                AuthenticateOld();

            packet.Write(Crypt.Get411Password(Settings.Password, encryptionSeed));
            if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null)
                packet.WriteString(Settings.Database);
            else
                packet.WriteString(""); // Add a null termination to the string.

            if (Settings.IntegratedSecurity)
            {
                // Append authentication method after the database name in the
                // handshake authentication packet.If we're sending CHANGE_USER
                // also write charset number after database name prior to plugin name
                if (reset)
                {
                    packet.WriteInteger(8, 2); // Charset number
                }
                packet.WriteString(AuthenticationWindowsPlugin);
                stream.SendPacket(packet);
                AuthenticateSSPI();
                return;
            }
            else
            {
                stream.SendPacket(packet);
            }

            // this result means the server wants us to send the password using
            // old encryption
            packet = stream.ReadPacket();
            if (packet.IsLastPacket)
            {
                packet.Clear();
                packet.WriteString(Crypt.EncryptPassword(
                                       Settings.Password, encryptionSeed.Substring(0, 8), true));
                stream.SendPacket(packet);
                ReadOk(true);
            }
            ReadOk(false);
        }
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
                    string pipeName = Settings.PipeName;
                    if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                        pipeName = null;
            #if !DNX
                    StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,Settings.Keepalive);
            #else
                    StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, Settings.Keepalive);
            #endif
                    baseStream = sc.GetStream(Settings.ConnectionTimeout);
                }
            }
            catch (Exception ex)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                    (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }

            if (baseStream == null)
                throw new MySqlException(Resources.UnableToConnectToHost,
                    (int)MySqlErrorCode.UnableToConnectToHost);

            int maxSinglePacket = 255 * 255 * 255;
            stream = new MySqlStream(baseStream, Encoding, false);

            stream.ResetTimeout((int)Settings.ConnectionTimeout * 1000);

            // read off the welcome packet and parse out it's values
            packet = stream.ReadPacket();
            int protocol = packet.ReadByte();
            string versionString = packet.ReadString();
            version = DBVersion.Parse(versionString);
            if (!version.isAtLeast(5, 0, 0))
                throw new NotSupportedException(Resources.ServerTooOld);
            threadId = packet.ReadInteger(4);
            encryptionSeed = packet.ReadString();

            maxSinglePacket = (256 * 256 * 256) - 1;

            // read in Server capabilities if they are provided
            ClientFlags serverCaps = 0;
            if (packet.HasMoreData)
                serverCaps = (ClientFlags)packet.ReadInteger(2);

            /* New protocol with 16 bytes to describe server characteristics */
            owner.ConnectionCharSetIndex = (int)packet.ReadByte();

            serverStatus = (ServerStatusFlags)packet.ReadInteger(2);

            // Since 5.5, high bits of server caps are stored after status.
            // Previously, it was part of reserved always 0x00 13-byte filler.
            uint serverCapsHigh = (uint)packet.ReadInteger(2);
            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            string seedPart2 = packet.ReadString();
            encryptionSeed += seedPart2;

            string authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);

            #if !CF
            if ((serverCaps & ClientFlags.SSL) == 0)
            {
                if ((Settings.SslMode != MySqlSslMode.None)
                && (Settings.SslMode != MySqlSslMode.Preferred))
                {
                    // Client requires SSL connections.
                    string message = String.Format(Resources.NoServerSSLSupport,
                        Settings.Server);
                    throw new MySqlException(message);
                }
            }
            else if (Settings.SslMode != MySqlSslMode.None)
            {
                stream.SendPacket(packet);
                StartSSL();
                packet.Clear();
                packet.WriteInteger((int)connectionFlags, 4);
            }
            #endif

            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(8);
            packet.Write(new byte[23]);

            Authenticate(false);

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
                stream = new MySqlStream(baseStream, Encoding, true);

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            packet.Version = version;
            stream.MaxBlockSize = maxSinglePacket;
        }
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
                    string pipeName = Settings.PipeName;
                    if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                    {
                        pipeName = null;
                    }
                    StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName, Settings.Keepalive);
                    baseStream = sc.GetStream(Settings.ConnectionTimeout);
                }
            }
            catch (Exception ex)
            {
                throw new MySqlException(ResourceStrings.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }

            if (baseStream == null)
            {
                throw new MySqlException(ResourceStrings.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost);
            }

            int maxSinglePacket = 255 * 255 * 255;

            stream = new MySqlStream(baseStream, Encoding, false);

            stream.ResetTimeout((int)Settings.ConnectionTimeout * 1000);

            // read off the welcome packet and parse out it's values
            packet = stream.ReadPacket();
            int    protocol      = packet.ReadByte();
            string versionString = packet.ReadString();

            version = DBVersion.Parse(versionString);
            if (!version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(ResourceStrings.ServerTooOld);
            }
            threadId       = packet.ReadInteger(4);
            encryptionSeed = packet.ReadString();

            maxSinglePacket = (256 * 256 * 256) - 1;

            // read in Server capabilities if they are provided
            ClientFlags serverCaps = 0;

            if (packet.HasMoreData)
            {
                serverCaps = (ClientFlags)packet.ReadInteger(2);
            }

            /* New protocol with 16 bytes to describe server characteristics */
            owner.ConnectionCharSetIndex = (int)packet.ReadByte();

            serverStatus = (ServerStatusFlags)packet.ReadInteger(2);

            // Since 5.5, high bits of server caps are stored after status.
            // Previously, it was part of reserved always 0x00 13-byte filler.
            uint serverCapsHigh = (uint)packet.ReadInteger(2);

            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            string seedPart2 = packet.ReadString();

            encryptionSeed += seedPart2;

            string authenticationMethod = "";

            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);
            if ((serverCaps & ClientFlags.SSL) == 0)
            {
                if ((Settings.SslMode != MySqlSslMode.None) &&
                    (Settings.SslMode != MySqlSslMode.Preferred))
                {
                    // Client requires SSL connections.
                    string message = String.Format(ResourceStrings.NoServerSSLSupport,
                                                   Settings.Server);
                    throw new MySqlException(message);
                }
            }
            else if (Settings.SslMode != MySqlSslMode.None)
            {
                stream.SendPacket(packet);
                StartSSL();
                packet.Clear();
                packet.WriteInteger((int)connectionFlags, 4);
            }
            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(8);
            packet.Write(new byte[23]);

            Authenticate(false);

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                stream = new MySqlStream(baseStream, Encoding, true);
            }

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            packet.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;
        }