Ejemplo n.º 1
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length,
    bool nullVal)
    {
      if (nullVal)
        return new MySqlDouble(true);

      if (length == -1)
      {
        byte[] b = new byte[8];
        packet.Read(b, 0, 8);
        return new MySqlDouble(BitConverter.ToDouble(b, 0));
      }
      string s = packet.ReadString(length);
      double d;
      try
      {
        d = Double.Parse(s, CultureInfo.InvariantCulture);
      }
      catch (OverflowException)
      {
        // MySQL server < 5.5 can return values not compatible with
        // Double.Parse(), i.e out of range for double.

        if (s.StartsWith("-", StringComparison.Ordinal))
          d = double.MinValue;
        else
          d = double.MaxValue;
      }
      return new MySqlDouble(d);
    }
Ejemplo n.º 2
0
    void IMySqlValue.WriteValue(MySqlPacket packet, 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)
      {
        if (ts.Milliseconds > 0)
          packet.WriteByte(12);
        else
          packet.WriteByte(8);

        packet.WriteByte((byte)(negative ? 1 : 0));        
        packet.WriteInteger(ts.Days, 4);
        packet.WriteByte((byte)ts.Hours);
        packet.WriteByte((byte)ts.Minutes);
        packet.WriteByte((byte)ts.Seconds);
        if (ts.Milliseconds > 0)
        {
          long mval = ts.Milliseconds*1000;
          packet.WriteInteger(mval, 4);          
        }
      }
      else
      {
        String s = String.Format("'{0}{1} {2:00}:{3:00}:{4:00}.{5:0000000}'",
            negative ? "-" : "", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Ticks % 10000000);
			
        packet.WriteStringNoNull(s);
      }
    }
Ejemplo n.º 3
0
    void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
    {
      Guid guid = Guid.Empty;
      string valAsString = val as string;
      byte[] valAsByte = val as byte[];

      if (val is Guid)
        guid = (Guid)val;
      else
      {
        try
        {
          if (valAsString != null)
            guid = new Guid(valAsString);
          else if (valAsByte != null)
            guid = new Guid(valAsByte);
        }
        catch (Exception ex)
        {
          throw new MySqlException(Resources.DataNotInSupportedFormat, ex);
        }
      }

      if (OldGuids)
        WriteOldGuid(packet, guid, binary);
      else
      {
        guid.ToString("D");

        if (binary)
          packet.WriteLenString(guid.ToString("D"));
        else
          packet.WriteStringNoNull("'" + MySqlHelper.EscapeString(guid.ToString("D")) + "'");
      }
    }
Ejemplo n.º 4
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object v, int length)
 {
   uint val = (v is uint) ? (uint)v : Convert.ToUInt32(v);
   if (binary)
     packet.WriteInteger((long)val, is24Bit ? 3 : 4);
   else
     packet.WriteStringNoNull(val.ToString());
 }
Ejemplo n.º 5
0
 public void WriteValue(MySqlPacket packet, bool binary, object value, int length)
 {
   ulong v = (value is UInt64) ? (UInt64)value : Convert.ToUInt64(value);
   if (binary)
     packet.WriteInteger((long)v, 8);
   else
     packet.WriteStringNoNull(v.ToString());
 }
Ejemplo n.º 6
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   double v = (val is double) ? (double)val : Convert.ToDouble(val);
   if (binary)
     packet.Write(BitConverter.GetBytes(v));
   else
     packet.WriteStringNoNull(v.ToString("R", CultureInfo.InvariantCulture));
 }
Ejemplo n.º 7
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   long v = (val is Int64) ? (Int64)val : Convert.ToInt64(val);
   if (binary)
     packet.WriteInteger(v, 8);
   else
     packet.WriteStringNoNull(v.ToString());
 }
Ejemplo n.º 8
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   int v = (val is Int32) ? (int)val : Convert.ToInt32(val);
   if (binary)
     packet.WriteInteger((long)v, is24Bit ? 3 : 4);
   else
     packet.WriteStringNoNull(v.ToString());
 }
Ejemplo n.º 9
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   int v = (val is UInt16) ? (UInt16)val : Convert.ToUInt16(val);
   if (binary)
     packet.WriteInteger((long)v, 2);
   else
     packet.WriteStringNoNull(v.ToString());
 }
Ejemplo n.º 10
0
 void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
 {
   byte v = (val is byte) ? (byte)val : Convert.ToByte(val);
   if (binary)
     packet.WriteByte(v);
   else
     packet.WriteStringNoNull(v.ToString());
 }
Ejemplo n.º 11
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlUInt16(true);

      if (length == -1)
        return new MySqlUInt16((ushort)packet.ReadInteger(2));
      else
        return new MySqlUInt16(UInt16.Parse(packet.ReadString(length)));
    }
Ejemplo n.º 12
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlUByte(true);

      if (length == -1)
        return new MySqlUByte((byte)packet.ReadByte());
      else
        return new MySqlUByte(Byte.Parse(packet.ReadString(length)));
    }
Ejemplo n.º 13
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlInt64(true);

      if (length == -1)
        return new MySqlInt64((long)packet.ReadULong(8));
      else
        return new MySqlInt64(Int64.Parse(packet.ReadString(length)));
    }
Ejemplo n.º 14
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, 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)packet.ReadInteger(4));
      else
        return new MySqlUInt32((this as IMySqlValue).MySqlDbType,
                     UInt32.Parse(packet.ReadString(length), NumberStyles.Any, CultureInfo.InvariantCulture));
    }
Ejemplo n.º 15
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlString(type, true);

      string s = String.Empty;
      if (length == -1)
        s = packet.ReadLenString();
      else
        s = packet.ReadString(length);
      MySqlString str = new MySqlString(type, s);
      return str;
    }
Ejemplo n.º 16
0
        public MySqlStream(Encoding encoding)
        {
            // we have no idea what the real value is so we start off with the max value
            // The real value will be set in NativeDriver.Configure()
            maxPacketSize = ulong.MaxValue;

            // we default maxBlockSize to MaxValue since we will get the 'real' value in 
            // the authentication handshake and we know that value will not exceed 
            // true maxBlockSize prior to that.
            maxBlockSize = Int32.MaxValue;

            packet = new MySqlPacket(encoding);
        }
Ejemplo n.º 17
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlSingle(true);

      if (length == -1)
      {
        byte[] b = new byte[4];
        packet.Read(b, 0, 4);
        return new MySqlSingle(BitConverter.ToSingle(b, 0));
      }
      return new MySqlSingle(Single.Parse(packet.ReadString(length),
     CultureInfo.InvariantCulture));
    }
Ejemplo n.º 18
0
        void IMySqlValue.WriteValue(MySqlPacket packet, 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)
                packet.WriteLenString(v);
            else
                packet.WriteStringNoNull("'" + MySqlHelper.EscapeString(v) + "'");
        }
Ejemplo n.º 19
0
    public IMySqlValue ReadValue(MySqlPacket packet, long length, bool isNull)
    {
      this.isNull = isNull;
      if (isNull)
        return this;

      if (length == -1)
        length = packet.ReadFieldLength();

      if (ReadAsString)
        mValue = UInt64.Parse(packet.ReadString(length));
      else
        mValue = (UInt64)packet.ReadBitValue((int)length);
      return this;
    }
Ejemplo n.º 20
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {
      if (nullVal)
        return new MySqlByte(true);

      if (length == -1)
        return new MySqlByte((sbyte)packet.ReadByte());
      else
      {
        string s = packet.ReadString(length);
        MySqlByte b = new MySqlByte(SByte.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture));
        b.TreatAsBoolean = TreatAsBoolean;
        return b;
      }
    }
Ejemplo n.º 21
0
    public override void SendQuery(MySqlPacket p)
    {
      rowSizeInBytes = 0;
      string cmdText = Encoding.GetString(p.Buffer, 5, p.Length - 5);
      string normalized_query = null;

      if (cmdText.Length > 300)
      {
        QueryNormalizer normalizer = new QueryNormalizer();
        normalized_query = normalizer.Normalize(cmdText);
        cmdText = cmdText.Substring(0, 300);
      }

      base.SendQuery(p);

      MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryOpened,
          Resources.TraceQueryOpened, driverId, ThreadID, cmdText);
      if (normalized_query != null)
        MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryNormalized,
            Resources.TraceQueryNormalized, driverId, ThreadID, normalized_query);
    }
Ejemplo n.º 22
0
    void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length)
    {
      byte[] buffToWrite = (val as byte[]);
      if (buffToWrite == null)
      {
        char[] valAsChar = (val as Char[]);
        if (valAsChar != null)
          buffToWrite = packet.Encoding.GetBytes(valAsChar);
        else
        {
          string s = val.ToString();
          if (length == 0)
            length = s.Length;
          else
            s = s.Substring(0, length);
          buffToWrite = packet.Encoding.GetBytes(s);
        }
      }

      // we assume zero length means write all of the value
      if (length == 0)
        length = buffToWrite.Length;

      if (buffToWrite == null)
        throw new MySqlException("Only byte arrays and strings can be serialized by MySqlBinary");

      if (binary)
      {
        packet.WriteLength(length);
        packet.Write(buffToWrite, 0, length);
      }
      else
      {
        packet.WriteStringNoNull("_binary ");
        packet.WriteByte((byte)'\'');
        EscapeByteArray(buffToWrite, length, packet);
        packet.WriteByte((byte)'\'');
      }
    }
Ejemplo n.º 23
0
 void IMySqlValue.SkipValue(MySqlPacket packet)
 {
   packet.Position += 4;
 }
Ejemplo n.º 24
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                baseStream = StreamCreator.GetStream(Settings);
#if NET46
                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);
            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 ((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(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;
        }
Ejemplo n.º 25
0
 internal MySqlPacket ReadPacket()
 {
     return(packet = stream.ReadPacket());
 }
Ejemplo n.º 26
0
    IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal)
    {

      if (nullVal) return new MySqlDateTime(type, true);

      if (length >= 0)
      {
        string value = packet.ReadString(length);
        return ParseMySql(value);
      }

      long bufLength = packet.ReadByte();
      int year = 0, month = 0, day = 0;
      int hour = 0, minute = 0, second = 0, microsecond = 0;
      if (bufLength >= 4)
      {
        year = packet.ReadInteger(2);
        month = packet.ReadByte();
        day = packet.ReadByte();
      }

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

      if (bufLength > 7)
      {
        microsecond = packet.Read3ByteInt();
        packet.ReadByte();
      }

      return new MySqlDateTime(type, year, month, day, hour, minute, second, microsecond);
    }
Ejemplo n.º 27
0
 void IMySqlValue.SkipValue(MySqlPacket packet)
 {
   int len = packet.ReadByte();
   packet.Position += len;
 }
Ejemplo n.º 28
0
    private void SerializeText(MySqlPacket packet, MySqlDateTime value)
    {
      string val = String.Empty;

      val = String.Format("{0:0000}-{1:00}-{2:00}",
                value.Year, value.Month, value.Day);
      if (type != MySqlDbType.Date)
      {
        val = value.Microsecond > 0 ? String.Format("{0} {1:00}:{2:00}:{3:00}.{4:000000}", val,
          value.Hour, value.Minute, value.Second, value.Microsecond) : String.Format("{0} {1:00}:{2:00}:{3:00} ", val,
          value.Hour, value.Minute, value.Second);
      }

      packet.WriteStringNoNull("'" + val + "'");
    }
Ejemplo n.º 29
0
    void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object value, int length)
    {
      MySqlDateTime dtValue;

      string valueAsString = value as string;

      if (value is DateTime)
        dtValue = new MySqlDateTime(type, (DateTime)value);
      else if (valueAsString != null)
        dtValue = MySqlDateTime.Parse(valueAsString);
      else if (value is MySqlDateTime)
        dtValue = (MySqlDateTime)value;
      else
        throw new MySqlException("Unable to serialize date/time value.");

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

      if (dtValue.Microsecond > 0)
        packet.WriteByte(11);
      else
        packet.WriteByte(7);

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

      if (dtValue.Microsecond > 0)
      {
        long val = dtValue.Microsecond;
        for (int x = 0; x < 4; x++)
        {
          packet.WriteByte((byte)(val & 0xff));
          val >>= 8;
        }
      }
    }
Ejemplo n.º 30
0
 void IMySqlValue.SkipValue(MySqlPacket packet)
 {
     int len = (int)packet.ReadFieldLength();
     packet.Position += len;
 }
Ejemplo n.º 31
0
 private void ReadEOF()
 {
     packet = stream.ReadPacket();
     CheckEOF();
 }
Ejemplo n.º 32
0
        public IMySqlValue ReadValue(MySqlPacket packet, long length, bool isNull)
        {
            if (isNull)
                return new MySqlJson(true);

            string s = String.Empty;
            if (length == -1)
                s = packet.ReadLenString();
            else
                s = packet.ReadString(length);
            MySqlJson str = new MySqlJson(s);
            return str;
        }
Ejemplo n.º 33
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,
                                    MySqlPacket packet, string parmName, int parameterIndex)
    {
      MySqlParameter parameter = null;

      if (!parameters.containsUnnamedParameters)
        parameter = parameters.GetParameterFlexible(parmName, false);
      else
      {
        if (parameterIndex <= parameters.Count)
          parameter = parameters[parameterIndex];
        else
          throw new MySqlException(Resources.ParameterIndexNotFound);
      }

      if (parameter == null)
      {
        // if we are allowing user variables and the parameter name starts with @
        // then we can't throw an exception
        if (parmName.StartsWith("@", StringComparison.Ordinal) && ShouldIgnoreMissingParameter(parmName))
          return false;
        throw new MySqlException(
            String.Format(Resources.ParameterMustBeDefined, parmName));
      }
      parameter.Serialize(packet, false, Connection.Settings);
      return true;
    }
Ejemplo n.º 34
0
 internal void SendPacket(MySqlPacket p)
 {
     stream.SendPacket(p);
 }