Summary description for MySqlStream.
Exemple #1
0
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			if (!(val is TimeSpan))
				throw new MySqlException("Only TimeSpan objects can be serialized by MySqlTimeSpan");

			TimeSpan ts = (TimeSpan)val;
            bool negative = ts.TotalMilliseconds < 0;
            ts = ts.Duration();

			if (binary)
			{
				stream.WriteByte(8);
				stream.WriteByte((byte)(negative ? 1 : 0));
				stream.WriteInteger(ts.Days, 4);
				stream.WriteByte((byte)ts.Hours);
				stream.WriteByte((byte)ts.Minutes);
				stream.WriteByte((byte)ts.Seconds);
			}
			else
			{
                String s = String.Format("'{0}{1} {2:00}:{3:00}:{4:00}.{5}'",
                    negative ? "-" : "", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);

				stream.WriteStringNoNull(s);
			}
		}
Exemple #2
0
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			byte v = ((IConvertible)val).ToByte(null);
            if (binary)
                stream.WriteByte((byte)v);
            else
                stream.WriteStringNoNull(v.ToString());
        }
Exemple #3
0
		public void WriteValue(MySqlStream stream, bool binary, object value, int length)
		{
			ulong v = Convert.ToUInt64(value);
			if (binary)
				stream.Write(BitConverter.GetBytes(v));
			else
				stream.WriteStringNoNull(v.ToString());
		}
Exemple #4
0
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			int v = Convert.ToInt32(val);
			if (binary)
				stream.Write(BitConverter.GetBytes(v));
			else
				stream.WriteStringNoNull(v.ToString());
		}
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			Single v = Convert.ToSingle(val);
			if (binary)
				stream.Write(BitConverter.GetBytes(v));
			else
				stream.WriteStringNoNull(v.ToString("R",
					 CultureInfo.InvariantCulture));
		}
Exemple #6
0
        internal void Serialize(MySqlStream stream, bool binary)
        {
            IMySqlValue v = MySqlField.GetIMySqlValue(mySqlDbType);

            if (!binary && (paramValue == null || paramValue == DBNull.Value))
                stream.WriteStringNoNull("NULL");
            else
                v.WriteValue(stream, binary, paramValue, size);
        }
    private void StartSSL()
    {
      RemoteCertificateValidationCallback sslValidateCallback =
          new RemoteCertificateValidationCallback(ServerCheckValidation);
      SslStream ss = new SslStream(baseStream, true, sslValidateCallback, null);
      X509CertificateCollection certs = GetClientCertificates();
      ss.AuthenticateAsClient(Settings.Server, certs, SslProtocols.Default, false);
      baseStream = ss;
      stream = new MySqlStream(ss, Encoding, false);
      stream.SequenceByte = 2;

    }
		void IMySqlValue.SkipValue(MySqlStream stream)
		{
			int len = stream.ReadByte();
			stream.SkipBytes(len);
		}
		void IMySqlValue.SkipValue(MySqlStream stream)
		{
			long len = stream.ReadFieldLength();
			stream.SkipBytes((int)len);
		}
Exemple #10
0
		void IMySqlValue.SkipValue(MySqlStream stream)
		{
			stream.ReadByte();
		}
        public override void Open()
        {
            base.Open();

            // connect to one of our specified hosts
            try
            {
#if !CF
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
#endif
                string pipeName = Settings.PipeName;
                if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                {
                    pipeName = null;
                }
                StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName);
                baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
            }
#endif
            }
            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);

            // read off the welcome packet and parse out it's values
            stream.OpenPacket();
            protocol = stream.ReadByte();
            string versionString = stream.ReadString();
            version        = DBVersion.Parse(versionString);
            threadId       = stream.ReadInteger(4);
            encryptionSeed = stream.ReadString();

            if (version.isAtLeast(4, 0, 8))
            {
                maxSinglePacket = (256 * 256 * 256) - 1;
            }

            // read in Server capabilities if they are provided
            serverCaps = 0;
            if (stream.HasMoreData)
            {
                serverCaps = (ClientFlags)stream.ReadInteger(2);
            }
            if (version.isAtLeast(4, 1, 1))
            {
                /* New protocol with 16 bytes to describe server characteristics */
                serverCharSetIndex = stream.ReadInteger(1);

                serverStatus = (ServerStatusFlags)stream.ReadInteger(2);
                stream.SkipBytes(13);
                string seedPart2 = stream.ReadString();
                encryptionSeed += seedPart2;
            }

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

            stream.StartOutput(0, false);
            stream.WriteInteger((int)connectionFlags,
                                version.isAtLeast(4, 1, 0) ? 4 : 2);

#if !CF
            if (connectionString.UseSSL && (serverCaps & ClientFlags.SSL) != 0)
            {
                stream.Flush();

                StartSSL();

                stream.StartOutput(0, false);
                stream.WriteInteger((int)connectionFlags,
                                    version.isAtLeast(4, 1, 0) ? 4 : 2);
            }
#endif

            stream.WriteInteger(maxSinglePacket,
                                version.isAtLeast(4, 1, 0) ? 4 : 3);

            if (version.isAtLeast(4, 1, 1))
            {
                stream.WriteByte(8);
                stream.Write(new byte[23]);
            }

            Authenticate();

            // 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.
            stream.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;

            isOpen = true;
        }
        public override void Execute()
        {
            // if we are not prepared, then call down to our base
            if (!IsPrepared)
            {
                base.Execute();
                return;
            }

            MySqlStream stream = new MySqlStream(Driver.Encoding);

            //TODO: support long data here
            // create our null bitmap
            BitArray nullMap = new BitArray(Parameters.Count);

            // now we run through the parameters that PREPARE sent back and use
            // those names to index into the parameters the user gave us.
            // if the user set that parameter to NULL, then we set the null map
            // accordingly
            if (paramList != null)
            {
                for (int x = 0; x < paramList.Length; x++)
                {
                    MySqlParameter p = Parameters[paramList[x].ColumnName];
                    if (p.Value == DBNull.Value || p.Value == null)
                    {
                        nullMap[x] = true;
                    }
                }
            }
            byte[] nullMapBytes = new byte[(Parameters.Count + 7) / 8];

            // we check this because Mono doesn't ignore the case where nullMapBytes
            // is zero length.
            if (nullMapBytes.Length > 0)
            {
                nullMap.CopyTo(nullMapBytes, 0);
            }

            // start constructing our packet
            stream.WriteInteger(statementId, 4);
            stream.WriteByte((byte)pageSize);         // flags; always 0 for 4.1
            stream.WriteInteger(1, 4);                // interation count; 1 for 4.1
            stream.Write(nullMapBytes);
            //if (parameters != null && parameters.Count > 0)
            stream.WriteByte(1);                                // rebound flag
            //else
            //	packet.WriteByte( 0 );
            //TODO:  only send rebound if parms change

            // write out the parameter types
            if (paramList != null)
            {
                foreach (MySqlField param in paramList)
                {
                    MySqlParameter parm = Parameters[param.ColumnName];
                    stream.WriteInteger((long)parm.GetPSType(), 2);
                }

                // now write out all non-null values
                foreach (MySqlField param in paramList)
                {
                    int index = Parameters.IndexOf(param.ColumnName);
                    if (index == -1)
                    {
                        throw new MySqlException("Parameter '" + param.ColumnName +
                                                 "' is not defined.");
                    }
                    MySqlParameter parm = Parameters[index];
                    if (parm.Value == DBNull.Value || parm.Value == null)
                    {
                        continue;
                    }

                    stream.Encoding = param.Encoding;
                    parm.Serialize(stream, true);
                }
            }

            executionCount++;

            Driver.ExecuteStatement(stream.InternalBuffer.ToArray());
        }
Exemple #13
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                var streamTask = StreamCreator.GetStream(Settings);
                streamTask.Wait();
                baseStream = streamTask.Result;

#if !CF && !RT && !NETSTANDARD1_3
                if (Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            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();
            owner.isFabric = versionString.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            version        = DBVersion.Parse(versionString);
            if (!owner.isFabric && !version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            threadId = packet.ReadInteger(4);

            byte[] seedPart1 = packet.ReadStringAsBytes();

            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;
            byte[] seedPart2 = packet.ReadStringAsBytes();
            encryptionSeed = new byte[seedPart1.Length + seedPart2.Length];
            seedPart1.CopyTo(encryptionSeed, 0);
            seedPart2.CopyTo(encryptionSeed, seedPart1.Length);

            string authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MySql versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

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

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);
            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(33); //character set utf-8
            packet.Write(new byte[23]);

#if !CF && !RT
            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);
                packet.WriteInteger(maxSinglePacket, 4);
                packet.WriteByte(33); //character set utf-8
                packet.Write(new byte[23]);
            }
#endif

#if RT
            if (Settings.SslMode != MySqlSslMode.None)
            {
                throw new NotImplementedException("SSL not supported in this WinRT release.");
            }
#endif

            Authenticate(authenticationMethod, 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 !CF
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
#endif
                string pipeName = Settings.PipeName;
                if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                {
                    pipeName = null;
                }
                StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,
                                                     Settings.Keepalive, this.Version);
#if !CF
                MySqlSecurityPermission.CreatePermissionSet(false).Assert();
#endif
                baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
            }
#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            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();

            //
            //	Patch: A.S. - Oct 28 2012
            //
            //versionString = "5.0.0";

            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;
        }
Exemple #15
0
 public SSPI(string targetName, MySqlStream stream, int seqNo, DBVersion version)
 {
   this.targetName = null;
   this.stream = stream;
   packetHeader = new byte[4];
   seq = seqNo;
   this.version = version;
 }
Exemple #16
0
        protected virtual void BindParameters()
        {
            // tokenize the sql
            ArrayList tokenArray = TokenizeSql(ResolvedCommandText);

            MySqlStream stream = new MySqlStream(Driver.Encoding);
            stream.Version = Driver.Version;

            // make sure our token array ends with a ;
            string lastToken = (string) tokenArray[tokenArray.Count - 1];
            if (lastToken != ";")
                tokenArray.Add(";");

            foreach (String token in tokenArray)
            {
                if (token.Trim().Length == 0)
                    continue;
                if (token == ";")
                {
                    buffers.Add(stream.InternalBuffer);
                    stream = new MySqlStream(Driver.Encoding);
                    continue;
                }
                if (token[0] == Parameters.ParameterMarker)
                {
                    if (SerializeParameter(Parameters, stream, token))
                        continue;
                }

                // our fall through case is to write the token to the byte stream
                stream.WriteStringNoNull(token);
            }
        }
Exemple #17
0
        /// <summary>
        /// Serializes the given parameter to the given memory stream
        /// </summary>
        /// <remarks>
        /// <para>This method is called by PrepareSqlBuffers to convert the given
        /// parameter to bytes and write those bytes to the given memory stream.
        /// </para>
        /// </remarks>
        /// <returns>True if the parameter was successfully serialized, false otherwise.</returns>
        private bool SerializeParameter(MySqlParameterCollection parameters,
            MySqlStream stream, string parmName)
        {
            MySqlParameter parameter = GetParameter(parameters, parmName);
            if (parameter == null)
            {
                // if we are using old syntax, we can't throw exceptions for parameters
                // not defined.
                if (Connection.Settings.UseOldSyntax)
                    return false;
                throw new MySqlException(
                    String.Format(Resources.ParameterMustBeDefined, parmName));
            }

            parameter.Serialize(stream, false);
            return true;
        }
Exemple #18
0
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlByte(true);

			if (length == -1)
				return new MySqlByte((sbyte)stream.ReadByte());
			else
			{
				string s = stream.ReadString(length);
				MySqlByte b = new MySqlByte(SByte.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture));
                b.TreatAsBoolean = TreatAsBoolean;
                return b;
			}
		}
Exemple #19
0
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlInt64(true);

			if (length == -1)
				return new MySqlInt64((long)stream.ReadLong(8));
			else
				return new MySqlInt64(Int64.Parse(stream.ReadString(length)));
		}
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlString(type, true);

			string s = String.Empty;
			if (length == -1)
				s = stream.ReadLenString();
			else
				s = stream.ReadString(length);
			MySqlString str = new MySqlString(type, s);
			return str;
		}
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlUInt32((this as IMySqlValue).MySqlDbType, true);

			if (length == -1)
				return new MySqlUInt32((this as IMySqlValue).MySqlDbType,
					 (uint)stream.ReadInteger(4));
			else
				return new MySqlUInt32((this as IMySqlValue).MySqlDbType,
					 UInt32.Parse(stream.ReadString(length), NumberStyles.Any, CultureInfo.InvariantCulture));
		}
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			string v = val.ToString();
            if (length > 0)
            {
                length = Math.Min(length, v.Length);
                v = v.Substring(0, length);
            }

			if (binary)
				stream.WriteLenString(v);
			else
				stream.WriteStringNoNull("'" + EscapeString(v) + "'");
		}
		private void SerializeText(MySqlStream stream, MySqlDateTime value)
		{
			string val = String.Empty;

			if (type == MySqlDbType.Timestamp && !stream.Version.isAtLeast(4, 1, 0))
				val = String.Format("{0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}",
					value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
			else
			{
				val = String.Format("{0:0000}-{1:00}-{2:00}",
                    value.Year, value.Month, value.Day);
                if (type != MySqlDbType.Date)
                    val = String.Format("{0}  {1:00}:{2:00}:{3:00}", val,
                        value.Hour, value.Minute, value.Second);
			}
			stream.WriteStringNoNull("'" + val + "'");
		}
Exemple #24
0
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal) return new MySqlTimeSpan(true);

			if (length >= 0)
			{
				string value = stream.ReadString(length);
				ParseMySql(value, stream.Version.isAtLeast(4, 1, 0));
				return this;
			}

			long bufLength = stream.ReadByte();
			int negate = 0;
			if (bufLength > 0)
				negate = stream.ReadByte();

			isNull = false;
			if (bufLength == 0)
				isNull = true;
			else if (bufLength == 5)
				mValue = new TimeSpan(stream.ReadInteger(4), 0, 0, 0);
			else if (bufLength == 8)
				mValue = new TimeSpan(stream.ReadInteger(4),
					 stream.ReadByte(), stream.ReadByte(), stream.ReadByte());
			else
				mValue = new TimeSpan(stream.ReadInteger(4),
					 stream.ReadByte(), stream.ReadByte(), stream.ReadByte(),
					 stream.ReadInteger(4) / 1000000);

			if (negate == 1)
				mValue = mValue.Negate();
			return this;
		}
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object value, int length)
		{
			MySqlDateTime dtValue;

			if (value is DateTime)
				dtValue = new MySqlDateTime(type, (DateTime)value);
			else if (value is string)
				dtValue = new MySqlDateTime(type, DateTime.Parse((string)value,
					 System.Globalization.CultureInfo.CurrentCulture));
			else if (value is MySqlDateTime)
				dtValue = (MySqlDateTime)value;
			else
				throw new MySqlException("Unable to serialize date/time value.");

			if (!binary)
			{
				SerializeText(stream, dtValue);
				return;
			}

			if (type == MySqlDbType.Timestamp)
				stream.WriteByte(11);
			else
				stream.WriteByte(7);

			stream.WriteInteger(dtValue.Year, 2);
			stream.WriteByte((byte)dtValue.Month);
			stream.WriteByte((byte)dtValue.Day);
			if (type == MySqlDbType.Date)
			{
				stream.WriteByte(0);
				stream.WriteByte(0);
				stream.WriteByte(0);
			}
			else
			{
				stream.WriteByte((byte)dtValue.Hour);
				stream.WriteByte((byte)dtValue.Minute);
				stream.WriteByte((byte)dtValue.Second);
			}

			if (type == MySqlDbType.Timestamp)
				stream.WriteInteger(dtValue.Millisecond, 4);
		}
    public void Open()
    {
      // connect to one of our specified hosts
      try
      {
#if !CF
        if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
        {
          SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
          str.Open(Settings.ConnectionTimeout);
          baseStream = str;
        }
        else
        {
#endif
          string pipeName = Settings.PipeName;
          if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
            pipeName = null;
          StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,
              Settings.Keepalive, this.Version);
#if !CF
         if (Settings.IncludeSecurityAsserts)
            MySqlSecurityPermission.CreatePermissionSet(false).Assert();
#endif
          baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
        }
#endif
      }
      catch (System.Security.SecurityException)
      {
        throw;
      }
      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();
      }
      else
      {
        // Some MySql versions like 5.1, don't give name of plugin, default to native password.
        authenticationMethod = "mysql_native_password";
      }

      // 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(authenticationMethod, 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;
    }
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal) return new MySqlDateTime(type, true);

			if (length >= 0)
			{
				string value = stream.ReadString(length);
				return ParseMySql(value, stream.Version.isAtLeast(4, 1, 0));
			}

			long bufLength = stream.ReadByte();
			int year = 0, month = 0, day = 0;
			int hour = 0, minute = 0, second = 0;

			if (bufLength >= 4)
			{
				year = stream.ReadInteger(2);
				month = stream.ReadByte();
				day = stream.ReadByte();
			}

			if (bufLength > 4)
			{
				hour = stream.ReadByte();
				minute = stream.ReadByte();
				second = stream.ReadByte();
			}

			if (bufLength > 7)
				stream.ReadInteger(4);

			return new MySqlDateTime(type, year, month, day, hour, minute, second);
		}
    public void Close(bool isOpen)
    {
      try
      {
        if (isOpen)
        {
          try
          {
            packet.Clear();
            packet.WriteByte((byte)DBCmd.QUIT);
            ExecutePacket(packet);
          }
          catch (Exception)
          {
            // Eat exception here. We should try to closing 
            // the stream anyway.
          }
        }

        if (stream != null)
          stream.Close();
        stream = null;
      }
      catch (Exception)
      {
        // we are just going to eat any exceptions
        // generated here
      }
    }
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                baseStream = StreamCreator.GetStream(Settings);
                //#if !CF && !RT
                //         if (Settings.IncludeSecurityAsserts)
                //            MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                //#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            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();
            owner.isFabric = versionString.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            version = DBVersion.Parse(versionString);
            if (!owner.isFabric && !version.isAtLeast(5, 0, 0))
                throw new NotSupportedException("Resources.ServerTooOld");

            threadId = packet.ReadInteger(4);

            byte[] seedPart1 = packet.ReadStringAsBytes();

            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;
            byte[] seedPart2 = packet.ReadStringAsBytes();
            encryptionSeed = new byte[seedPart1.Length + seedPart2.Length];
            seedPart1.CopyTo(encryptionSeed, 0);
            seedPart2.CopyTo(encryptionSeed, seedPart1.Length);

            string authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MySql versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

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

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);
            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(33); //character set utf-8
            packet.Write(new byte[23]);

            #if !CF && !RT
            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);
                packet.WriteInteger(maxSinglePacket, 4);
                packet.WriteByte(33); //character set utf-8
                packet.Write(new byte[23]);
            }
            #endif

            #if RT
              if (Settings.SslMode != MySqlSslMode.None)
              {
            throw new NotImplementedException("SSL not supported in this WinRT release.");
              }
            #endif

            Authenticate(authenticationMethod, 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;
        }
Exemple #30
0
        IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
        {
            if (nullVal)
                return new MySqlSingle(true);

            if (length == -1)
            {
                byte[] b = new byte[4];
                stream.Read(b, 0, 4);
                return new MySqlSingle(BitConverter.ToSingle(b, 0));
            }
            return new MySqlSingle(Single.Parse(stream.ReadString(length),
                     CultureInfo.InvariantCulture));
        }
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlDecimal(true);

			if (length == -1)
			{
				string s = stream.ReadLenString();
				return new MySqlDecimal(Decimal.Parse(s,
					 CultureInfo.InvariantCulture));
			}
			else
			{
				string s = stream.ReadString(length);
				return new MySqlDecimal(Decimal.Parse(s,
					 CultureInfo.InvariantCulture));
			}
		}
Exemple #32
0
		void IMySqlValue.SkipValue(MySqlStream stream)
		{
			stream.SkipBytes(2);
		}
		void IMySqlValue.WriteValue(MySqlStream stream, bool binary, object val, int length)
		{
			decimal v = Convert.ToDecimal(val);
			string valStr = v.ToString(CultureInfo.InvariantCulture);
			if (binary)
				stream.WriteLenString(valStr);
			else
				stream.WriteStringNoNull(valStr);
		}
Exemple #34
0
		IMySqlValue IMySqlValue.ReadValue(MySqlStream stream, long length, bool nullVal)
		{
			if (nullVal)
				return new MySqlInt16(true);

			if (length == -1)
				return new MySqlInt16((short)stream.ReadInteger(2));
			else
				return new MySqlInt16(Int16.Parse(stream.ReadString(length)));
		}
Exemple #35
0
        public void Open()
        {
            try
            {
                this.baseStream = StreamCreator.GetStream(this.Settings);
                if (this.Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception inner)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042, inner);
            }
            if (this.baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042);
            }
            this.stream = new MySqlStream(this.baseStream, this.Encoding, false);
            this.stream.ResetTimeout((int)(this.Settings.ConnectionTimeout * 1000u));
            this.packet = this.stream.ReadPacket();
            this.packet.ReadByte();
            string versionString = this.packet.ReadString();

            this.version = DBVersion.Parse(versionString);
            if (!this.version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            this.threadId       = this.packet.ReadInteger(4);
            this.encryptionSeed = this.packet.ReadString();
            int         num         = 16777215;
            ClientFlags clientFlags = (ClientFlags)0uL;

            if (this.packet.HasMoreData)
            {
                clientFlags = (ClientFlags)((long)this.packet.ReadInteger(2));
            }
            this.owner.ConnectionCharSetIndex = (int)this.packet.ReadByte();
            this.serverStatus = (ServerStatusFlags)this.packet.ReadInteger(2);
            uint num2 = (uint)this.packet.ReadInteger(2);

            clientFlags          |= (ClientFlags)(num2 << 16);
            this.packet.Position += 11;
            string str = this.packet.ReadString();

            this.encryptionSeed += str;
            string authMethod;

            if ((clientFlags & ClientFlags.PLUGIN_AUTH) != (ClientFlags)0uL)
            {
                authMethod = this.packet.ReadString();
            }
            else
            {
                authMethod = "mysql_native_password";
            }
            this.SetConnectionFlags(clientFlags);
            this.packet.Clear();
            this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            if ((clientFlags & ClientFlags.SSL) == (ClientFlags)0uL)
            {
                if (this.Settings.SslMode != MySqlSslMode.None && this.Settings.SslMode != MySqlSslMode.Preferred)
                {
                    string msg = string.Format(Resources.NoServerSSLSupport, this.Settings.Server);
                    throw new MySqlException(msg);
                }
            }
            else if (this.Settings.SslMode != MySqlSslMode.None)
            {
                this.stream.SendPacket(this.packet);
                this.StartSSL();
                this.packet.Clear();
                this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            }
            this.packet.WriteInteger((long)num, 4);
            this.packet.WriteByte(8);
            this.packet.Write(new byte[23]);
            this.Authenticate(authMethod, false);
            if ((this.connectionFlags & ClientFlags.COMPRESS) != (ClientFlags)0uL)
            {
                this.stream = new MySqlStream(this.baseStream, this.Encoding, true);
            }
            this.packet.Version      = this.version;
            this.stream.MaxBlockSize = num;
        }