Beispiel #1
0
        /// <summary>
        /// 获取玩家数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PlayerData GetPlayerData(string id)
        {
            PlayerData playerData = null;

            if (!IsSafeStr(id))
            {
                return(playerData);
            }

            string       cmdStr = string.Format("select * from player where id='{0}';", id);
            MySqlCommand cmd    = new MySqlCommand(cmdStr, sqlConn);

            byte[] buffer = null;
            try
            {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                //如果不包含数据
                if (!dataReader.HasRows)
                {
                    dataReader.Close();
                    return(playerData);
                }

                //读取第一行数据
                dataReader.Read();
                //获取要读取的数据长度
                long length = dataReader.GetBytes(1, 0, null, 0, 0);
                buffer = new byte[length];
                dataReader.GetBytes(1, 0, buffer, 0, (int)length);
                dataReader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("GetPlayerData:" + e.Message);
                return(playerData);
            }



            //反序列化
            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                playerData = (PlayerData)binaryFormatter.Deserialize(stream);
                return(playerData);
            }
            catch (Exception e)
            {
                Console.WriteLine("GetPlayDataDesFormatter:" + e.Message);
                return(playerData);
            }
        }
        public PlayerData GetPlayerData(string id)
        {
            PlayerData playerData = null;

            if (!IsSafeStr(id))
            {
                return(playerData);
            }

            string       cmdStr = string.Format("select * from player where id='{0}'", id);
            MySqlCommand cmd    = new MySqlCommand(cmdStr, sqlConn);

            byte[] buffer = new byte[1];
            //从数据库读取二进制大对象
            try {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                if (!dataReader.HasRows)
                {
                    dataReader.Close();
                    return(playerData);
                }
                dataReader.Read();

                //GetBytes:以字节的格式读取数据
                //参数一:读取哪个字段,第一个字段是0,第二个字段是1,......
                //参数二:从当前选中字段的第几个字节开始读取
                //参数三:写入到指定缓冲区
                //参数四:从指定缓冲区的第几个字节开始写入
                //参数五:最大读取字节数,G
                //返回值:指定字段的字节数,G
                long len = dataReader.GetBytes(1, 0, null, 0, 0);   //获得指定字段的字节数
                buffer = new byte[len];
                dataReader.GetBytes(1, 0, buffer, 0, (int)len);
                dataReader.Close();
            }
            catch (Exception e) {
                Console.WriteLine("[DataMgr]GetPlayerData 查询失败 " + e.Message);
                return(playerData);
            }

            //反序列化
            MemoryStream stream = new MemoryStream(buffer);

            try {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return(playerData);
            }
            catch (Exception e) {
                Console.WriteLine("[DataMgr]GetPlayerData 反序列化失败 " + e.Message);
                return(playerData);
            }
        }
Beispiel #3
0
        // 取 dr 中某字段的数据并返回
        public static object GetValue(DbColumn col, MySqlDataReader r, int idx)
        {
            switch (col.dataType)
            {
            case DbDataTypes.Boolean:
                return(r.GetBoolean(idx));

            case DbDataTypes.Int8:
                return(r.GetSByte(idx));

            case DbDataTypes.Int16:
                return(r.GetInt16(idx));

            case DbDataTypes.Int32:
                return(r.GetInt32(idx));

            case DbDataTypes.Int64:
                return(r.GetInt64(idx));

            case DbDataTypes.UInt8:
                return(r.GetByte(idx));

            case DbDataTypes.UInt16:
                return(r.GetUInt16(idx));

            case DbDataTypes.UInt32:
                return(r.GetUInt32(idx));

            case DbDataTypes.UInt64:
                return(r.GetUInt64(idx));

            case DbDataTypes.Float:
                return(r.GetFloat(idx));

            case DbDataTypes.Double:
                return(r.GetDouble(idx));

            case DbDataTypes.DateTime:
                return(r.GetDateTime(idx));

            case DbDataTypes.String:
                return(r.GetString(idx));

            case DbDataTypes.Bytes:
                var len = (int)r.GetBytes(idx, 0, null, 0, 0);
                var buf = new byte[len];
                r.GetBytes(idx, 0, buf, 0, len);
                return(buf);

            default:
                throw new Exception("unsupported DbType");
            }
        }
Beispiel #4
0
    public void TestMultiPacket()
    {
      int len = 20000000;

      st.suExecSQL("SET GLOBAL max_allowed_packet=64000000");

      // currently do not test this with compression
      if (st.conn.UseCompression) return;

      using (MySqlConnection c = new MySqlConnection(st.GetConnectionString(true)))
      {
        c.Open();
        byte[] dataIn = Utils.CreateBlob(len);
        byte[] dataIn2 = Utils.CreateBlob(len);

        MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, NULL, ?blob, NULL )", c);
        cmd.CommandTimeout = 0;
        cmd.Parameters.Add(new MySqlParameter("?id", 1));
        cmd.Parameters.Add(new MySqlParameter("?blob", dataIn));
        cmd.ExecuteNonQuery();

        cmd.Parameters[0].Value = 2;
        cmd.Parameters[1].Value = dataIn2;
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT * FROM Test";

        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
          reader.Read();
          byte[] dataOut = new byte[len];
          long count = reader.GetBytes(2, 0, dataOut, 0, len);
          Assert.Equal(len, count);
          int i = 0;
          try
          {
            for (; i < len; i++)
              Assert.Equal(dataIn[i], dataOut[i]);
          }
          catch (Exception)
          {
            int z = i;
          }

          reader.Read();
          count = reader.GetBytes(2, 0, dataOut, 0, len);
          Assert.Equal(len, count);

          for (int x = 0; x < len; x++)
            Assert.Equal(dataIn2[x], dataOut[x]);
        }
      }
    }
Beispiel #5
0
        public UserData GetUserData(string Openid)
        {
            MySqlConnection mySql = new MySqlConnection(Sqlconnstr);

            mySql.Open();
            UserData UD     = null;
            string   cmdStr = string.Format("select * from Player where ID='{0}';", Openid);

#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
            MySqlCommand cmd = new MySqlCommand(cmdStr, mySql);
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
            byte[] buffer = new byte[1];
            try
            {
                MySqlDataReader reader = cmd.ExecuteReader();
                if (!reader.HasRows)
                {
                    reader.Close();
                    mySql.Close();
                    cmd.Dispose();
                    return(UD);
                }
                reader.Read();
                long len = reader.GetBytes(3, 0, null, 0, 0);
                buffer = new byte[len];
                reader.GetBytes(3, 0, buffer, 0, (int)len);
                reader.Close();
                mySql.Close();
                cmd.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("[DataMgr] GetUserData" + e.Message);
                mySql.Close();
                cmd.Dispose();
                return(UD);
            }
            //反序列化
            MemoryStream stream = new MemoryStream(buffer);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                UD = (UserData)formatter.Deserialize(stream);
                stream.Dispose();
                return(UD);
            }
            catch (Exception e)
            {
                Console.WriteLine("[DataMgr] GetUserData反序列化" + e.Message);
                stream.Dispose();
                return(UD);
            }
        }
Beispiel #6
0
        private void queryReadInteral(ref Result result, ref MySqlCommand command)
        {
            // Create reader
            MySqlDataReader reader = command.ExecuteReader();

            // Read row-by-row
            byte[]       buffer;
            MemoryStream bufferMS;
            int          bufferOffset;
            int          bytesAvailable;
            ResultRow    row;
            int          t;

            while (reader.Read())
            {
                row = new ResultRow();
                for (t = 0; t < reader.FieldCount; t++)
                {
                    row.attributes.Add(reader.GetName(t), reader.IsDBNull(t) ? null : reader.GetValue(t));
                    // Check if the column of the row is a byte-array, if so -> add to separate byte dictionary
                    string dt = reader.GetDataTypeName(t);
                    if (dt == "BLOB" || dt == "TINYBLOB" || dt == "MEDIUMBLOB" || dt == "LONGBLOB")
                    {
                        bufferMS = new MemoryStream();
                        try
                        {
                            bufferOffset   = 0;
                            bytesAvailable = (int)reader.GetBytes(t, 0, null, 0, 0);
                            while (bufferOffset < bytesAvailable)
                            {
                                reader.GetBytes(t, bufferOffset, buffer = new byte[BYTE_BUFFER_SIZE], 0, BYTE_BUFFER_SIZE);
                                bufferMS.Write(buffer, 0, BYTE_BUFFER_SIZE);
                                bufferOffset += BYTE_BUFFER_SIZE;
                            }
                            bufferMS.Flush();
                            if (row.attributesByteArray == null)
                            {
                                row.attributesByteArray = new Dictionary <string, byte[]>();
                            }
                            row.attributesByteArray.Add(reader.GetName(t), bufferMS.ToArray());
                        }
                        catch { }
                        finally
                        {
                            bufferMS.Dispose();
                        }
                    }
                }
                result.tuples.Add(row);
            }
            reader.Close();
        }
        private static GtsRecord4 Record4FromReader(MySqlDataReader reader)
        {
            GtsRecord4 result = new GtsRecord4();

            byte[] data = new byte[236];
            reader.GetBytes(0, 0, data, 0, 236);
            result.Data = data;
            data        = null;

            result.Species           = reader.GetUInt16(1);
            result.Gender            = (Genders)reader.GetByte(2);
            result.Level             = reader.GetByte(3);
            result.RequestedSpecies  = reader.GetUInt16(4);
            result.RequestedGender   = (Genders)reader.GetByte(5);
            result.RequestedMinLevel = reader.GetByte(6);
            result.RequestedMaxLevel = reader.GetByte(7);
            result.Unknown1          = reader.GetByte(8);
            result.TrainerGender     = (GtsTrainerGenders)reader.GetByte(9);
            result.Unknown2          = reader.GetByte(10);
            if (reader.IsDBNull(11))
            {
                result.TimeDeposited = null;
            }
            else
            {
                result.TimeDeposited = reader.GetDateTime(11);
            }
            if (reader.IsDBNull(12))
            {
                result.TimeWithdrawn = null;
            }
            else
            {
                result.TimeWithdrawn = reader.GetDateTime(12);
            }
            result.PID = reader.GetInt32(13);

            data = new byte[16];
            reader.GetBytes(14, 0, data, 0, 16);
            result.TrainerName = new String4(data);
            data = null;

            result.TrainerOT       = reader.GetUInt16(15);
            result.TrainerCountry  = reader.GetByte(16);
            result.TrainerRegion   = reader.GetByte(17);
            result.TrainerClass    = reader.GetByte(18);
            result.IsExchanged     = reader.GetByte(19);
            result.TrainerVersion  = reader.GetByte(20);
            result.TrainerLanguage = reader.GetByte(21);

            return(result);
        }
Beispiel #8
0
        internal static byte[] ReadBlob(MySqlDataReader reader, string column)
        {
            long len = reader.GetBytes(reader.GetOrdinal(column), 0, null, 0, 0);

            if (len != 0)
            {
                var buffer = new byte[len];
                reader.GetBytes(reader.GetOrdinal(column), 0, buffer, 0, (int)len);

                return(buffer);
            }
            return(null);
        }
        public void Bug6271()
        {
            if (st.Version < new Version(4, 1))
            {
                return;
            }

            // Create the table again
            st.execSQL("CREATE TABLE `Test2` (id INT unsigned NOT NULL auto_increment, " +
                       "`xpDOSG_Name` text,`xpDOSG_Desc` text, `Avatar` MEDIUMBLOB, `dtAdded` DATETIME, `dtTime` TIMESTAMP, " +
                       "PRIMARY KEY(id)) ENGINE=InnoDB DEFAULT CHARSET=latin1");

            string sql = "INSERT INTO `Test2` (`xpDOSG_Name`,`dtAdded`, `xpDOSG_Desc`,`Avatar`, `dtTime`) " +
                         "VALUES(?name, ?dt, ?desc, ?Avatar, NULL)";

            MySqlCommand cmd = new MySqlCommand(sql, st.conn);

            DateTime dt = DateTime.Now;

            dt = dt.AddMilliseconds(dt.Millisecond * -1);

            byte[] xpDOSG_Avatar = Utils.CreateBlob(13000);
            cmd.Parameters.AddWithValue("?name", "Ceci est un nom");

            cmd.Parameters.AddWithValue("?desc", "Ceci est une description facile à plantouiller");
            cmd.Parameters.AddWithValue("?avatar", xpDOSG_Avatar);
            cmd.Parameters.AddWithValue("?dt", dt);
            cmd.Prepare();
            int count = cmd.ExecuteNonQuery();

            Assert.Equal(1, count);

            cmd.CommandText = "SELECT * FROM Test2";
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                Assert.True(reader.Read());
                Assert.Equal("Ceci est un nom", reader.GetString(1));
                Assert.Equal(dt.ToString("G"), reader.GetDateTime(4).ToString("G"));
                Assert.Equal("Ceci est une description facile à plantouiller", reader.GetString(2));

                long len = reader.GetBytes(3, 0, null, 0, 0);
                Assert.Equal(xpDOSG_Avatar.Length, len);
                byte[] outBytes = new byte[len];
                reader.GetBytes(3, 0, outBytes, 0, (int)len);

                for (int x = 0; x < xpDOSG_Avatar.Length; x++)
                {
                    Assert.Equal(xpDOSG_Avatar[x], outBytes[x]);
                }
            }
        }
Beispiel #10
0
        //获取玩家数据
        //public long Getbytes(int i,long dataIndex,byte[] buffer,int bufferIndex,int length)
        //i          ->从零开始的序列号,下述语句中0代表id,1代表data
        //dataIndex  ->字段中的索引,从dataIndex处开始读取操作
        //buffer     ->要将字节流读入的缓冲区
        //bufferIndex->buffer中写入操作开始位置的索引
        //length     ->要复制到缓冲区中的最大长度
        //返回值     ->实际读取到的字节流长度

        public PlayerData GetPlayerData(string id)
        {
            PlayerData playerData = null;

            //防SQL注入
            if (!IsSafeStr(id))
            {
                return(playerData);
            }
            //查询
            string       cmdStr = string.Format("Select * from player where id='{0}';", id);
            MySqlCommand cmd    = new MySqlCommand(cmdStr, sqlConn);

            byte[] buffer = new byte[1];
            try
            {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                if (!dataReader.HasRows)
                {
                    dataReader.Close();
                    return(playerData);
                }
                dataReader.Read();
                //读取数据集中第二个字段的方法,第一个参数1代表第二个字段data
                long len = dataReader.GetBytes(1, 0, null, 0, 0);
                buffer = new byte[len];
                dataReader.GetBytes(1, 0, buffer, 0, (int)len);
                dataReader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("[DataMgr]GetPlayerData查询" + e.Message);
                return(playerData);
            }

            //反序列化
            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return(playerData);
            }
            catch (Exception e)
            {
                Console.WriteLine("[DataMgr]GetPlayerData反序列化" + e.Message);
                return(playerData);
            }
        }
Beispiel #11
0
        //获取玩家数据
        public PlayerData GetPlayerData(string username)
        {
            PlayerData playerData = null;

            //防sql注入
            if (!IsSafeStr(username))
            {
                return(playerData);
            }
            //查询
            string       cmdStr = string.Format("SELECT * FROM userdatamsg WHERE username = '******';", username);
            MySqlCommand cmd    = new MySqlCommand(cmdStr, con);

            byte[] buffer = new byte[1];
            try
            {
                MySqlDataReader rdr = cmd.ExecuteReader();
                if (!rdr.HasRows)
                {
                    rdr.Close();
                    return(playerData);
                }
                rdr.Read();
                long len = rdr.GetBytes(1, 0, null, 0, 0);
                buffer = new byte[len];
                rdr.GetBytes(1, 0, buffer, 0, (int)len);
                rdr.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("[ServerSQL]GetPlayerData 查询" + e.Message);
                return(playerData);
            }

            //反序列化

            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return(playerData);
            }
            catch (Exception e)
            {
                Console.WriteLine("[ServerSQL]GetPlayerData 反序列化" + e.Message);
                return(playerData);
            }
        }
    //获取玩家数据
    public PlayerData GetPlayerData(string id)
    {
        PlayerData playerData = null;

        //防sql注入
        if (!IsSafeStr(id))
        {
            return(playerData);
        }
        //查询
        string       cmdStr = string.Format("select * from player where id ='{0}';", id);
        MySqlCommand cmd    = new MySqlCommand(cmdStr, sqlConn);

        byte[] buffer;
        try
        {
            MySqlDataReader dataReader = cmd.ExecuteReader();
            if (!dataReader.HasRows)
            {
                dataReader.Close();
                return(playerData);
            }
            dataReader.Read();

            long len = dataReader.GetBytes(1, 0, null, 0, 0);//1是data
            buffer = new byte[len];
            dataReader.GetBytes(1, 0, buffer, 0, (int)len);
            dataReader.Close();
        }
        catch (Exception e)
        {
            Logger.Default.Info("[DataMgr]GetPlayerData 查询 " + e.Message);
            return(playerData);
        }
        //反序列化
        MemoryStream stream = new MemoryStream(buffer);

        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            playerData = (PlayerData)formatter.Deserialize(stream);
            return(playerData);
        }
        catch (SerializationException e)
        {
            Logger.Default.Info("[DataMgr]GetPlayerData 反序列化 " + e.Message);
            return(playerData);
        }
    }
Beispiel #13
0
        public void Blobs()
        {
            execSQL("DROP TABLE IF EXISTS Test");
            execSQL("CREATE TABLE Test (id INT, blob1 LONGBLOB, text1 LONGTEXT)");

            MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?blob1, ?text1)", conn);

            cmd.Prepare();

            byte[] bytes = Utils.CreateBlob(400000);
            string inStr = "This is my text";

            cmd.Parameters.AddWithValue("?id", 1);
            cmd.Parameters.AddWithValue("?blob1", bytes);
            cmd.Parameters.AddWithValue("?text1", inStr);
            int count = cmd.ExecuteNonQuery();

            Assert.AreEqual(1, count);

            cmd.CommandText = "SELECT * FROM Test";
            cmd.Prepare();
            MySqlDataReader reader = null;

            try
            {
                reader = cmd.ExecuteReader();
                Assert.IsTrue(reader.Read());
                Assert.AreEqual(1, reader.GetInt32(0));
                Assert.AreEqual(bytes.Length, reader.GetBytes(1, 0, null, 0, 0));
                byte[] outBytes = new byte[bytes.Length];
                reader.GetBytes(1, 0, outBytes, 0, bytes.Length);
                for (int x = 0; x < bytes.Length; x++)
                {
                    Assert.AreEqual(bytes[x], outBytes[x]);
                }
                Assert.AreEqual(inStr, reader.GetString(2));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Beispiel #14
0
        private byte[] GetBytesFromColumn(MySqlDataReader reader, int column)
        {
            int length = (int)reader.GetBytes(column, 0, null, 0, 0);

            byte[] buffer = new byte[length];
            int    index  = 0;

            while (index < length)
            {
                int bytesRead = (int)reader.GetBytes(column, index,
                                                     buffer, index, length - index);
                index += bytesRead;
            }
            return(buffer);
        }
Beispiel #15
0
        public PlayerData GettPlayerData(string id)
        {
            PlayerData playerData = null;

            if (!isSafeStr(id))
            {
                return(playerData);
            }
            string       cmdStr = "select * from player where id ='" + id + "';";
            MySqlCommand cmd    = new MySqlCommand(cmdStr, sqlConn);

            byte[] buffer = new byte[1];
            try
            {
                MySqlDataReader rder = cmd.ExecuteReader();
                if (!rder.HasRows)
                {
                    Console.WriteLine("没有获取到角色信息");
                    rder.Close();
                    return(playerData);
                }
                rder.Read();
                long len = rder.GetBytes(1, 0, null, 0, 0);
                buffer = new byte[len];
                rder.GetBytes(1, 0, buffer, 0, (int)len);
                rder.Close();
            }

            catch (Exception e)
            {
                Console.WriteLine("*****");
                Console.WriteLine("读取失败" + e.Message);
                return(playerData);
            }
            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return(playerData);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("[DataMgr]GetPlayerData 反序列化" + e.Message);
                return(playerData);
            }
        }
Beispiel #16
0
        //获取角色数据
        public PlayerData GetPlayerData(string Openid)
        {
            MySqlConnection mySql = new MySqlConnection(Sqlconnstr);

            mySql.Open();
            PlayerData playerData = null;
            string     cmdStr     = string.Format("select * from Player where ID='{0}';", Openid);

            byte[] buffer = new byte[1];
            using (MySqlCommand cmd = new MySqlCommand(cmdStr, mySql))
            {
                try
                {
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (!reader.HasRows)
                    {
                        reader.Close();
                        return(playerData);
                    }
                    reader.Read();
                    long len = reader.GetBytes(1, 0, null, 0, 0);
                    buffer = new byte[len];
                    reader.GetBytes(1, 0, buffer, 0, (int)len);
                    reader.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("[DataMgr] GetPlayerData 查询" + e.Message + Thread.CurrentThread.Name);
                    return(playerData);
                }
                mySql.Close();
                cmd.Dispose();
            }
            //反序列化
            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return(playerData);
            }
            catch (Exception e)
            {
                Console.WriteLine("[DataMgr] GetPlayerData 反序列化" + e.Message);
                return(playerData);
            }
        }
Beispiel #17
0
        public void MediumIntBlobSize()
        {
            execSQL("CREATE TABLE test (id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, " +
                    "image MEDIUMBLOB NOT NULL, imageSize MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT 0, " +
                    "PRIMARY KEY (id))");

            byte[] image = new byte[2048];
            for (int x = 0; x < image.Length; x++)
            {
                image[x] = (byte)(x % 47);
            }
            MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES(NULL, ?image, ?size)", conn);

            cmd.Parameters.AddWithValue("?image", image);
            cmd.Parameters.AddWithValue("?size", image.Length);
            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT imageSize, length(image), image FROM test WHERE id=?id";
            cmd.Parameters.AddWithValue("?id", 1);
            cmd.Prepare();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                reader.Read();
                uint actualsize = reader.GetUInt32(1);
                Assert.AreEqual(image.Length, actualsize);
                uint   size     = reader.GetUInt32(0);
                byte[] outImage = new byte[size];
                long   len      = reader.GetBytes(reader.GetOrdinal("image"), 0, outImage, 0, (int)size);
                Assert.AreEqual(image.Length, size);
                Assert.AreEqual(image.Length, len);
            }
        }
Beispiel #18
0
        public static bool LoginPlayer(string username, string password, ref long accountid, ref bool banned, ref long role)
        {
            MySqlDataReader reader = null;

            if (Database.Query(ref reader, "SELECT accountID, password, banned, role FROM account WHERE accountName = '" + Database.DoEscapeString(username) + "' AND password=SHA1('" + Database.DoEscapeString(password) + "')") == false)
            {
                return(false);
            }

            if (reader.Read() == false)
            {
                reader.Close();
                return(false);
            }

            accountid = reader.GetInt64(0);
            banned    = reader.GetBoolean(2);
            role      = reader.GetInt64(3);

            SHA1 sha1 = SHA1.Create();

            sha1.Initialize();
            byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes(password));
            byte[] outb = new byte[hash.Length];

            reader.GetBytes(1, 0, outb, 0, outb.Length);
            reader.Close();

            return(true);
        }
Beispiel #19
0
 bool ISimulationDataTerrainStorageInterface.TryGetDefault(UUID regionID, List <LayerPatch> list)
 {
     using (var connection = new MySqlConnection(m_ConnectionString))
     {
         connection.Open();
         using (var cmd = new MySqlCommand("SELECT PatchID, TerrainData FROM defaultterrains WHERE RegionID = @regionid", connection))
         {
             cmd.Parameters.AddParameter("@regionid", regionID);
             cmd.CommandTimeout = 3600;
             using (MySqlDataReader dbReader = cmd.ExecuteReader())
             {
                 while (dbReader.Read())
                 {
                     var patch = new LayerPatch
                     {
                         ExtendedPatchID = dbReader.GetUInt32("PatchID"),
                         Serialization   = dbReader.GetBytes("TerrainData")
                     };
                     list.Add(patch);
                 }
             }
         }
     }
     return(list.Count != 0);
 }
Beispiel #20
0
        /// <summary>
        /// Search for owner market items
        /// </summary>
        /// <returns></returns>
        public IEnumerable <MarketItemArgument> SearchMarketForOwner(Character target)
        {
            MySqlConnection connection = ConnectionPool.Request();
            MySqlCommand    command    = new MySqlCommand(_query_09, connection);

            command.Parameters.AddWithValue("?CharId", target.ModelId);
            MySqlDataReader reader = null;

            try
            {
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    byte[]             buffer = new byte[67];
                    MarketItemArgument item   = new MarketItemArgument();
                    item.id      = reader.GetUInt32(0);
                    item.sender  = reader.GetString(4);
                    item.price   = reader.GetUInt32(7);
                    item.expires = reader.GetMySqlDateTime(9).GetDateTime();
                    reader.GetBytes(8, 0, buffer, 0, 67);
                    Rag2Item.Deserialize(out item.item, buffer, 0);
                    yield return(item);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                ConnectionPool.Release(connection);
            }
        }
Beispiel #21
0
        public void ReadBinary16AsBinary()
        {
            execSQL("DROP TABLE IF EXISTS Test");
            execSQL("CREATE TABLE Test (id INT, guid BINARY(16))");

            string connStr = GetConnectionString(true) + ";old guids=true";

            using (MySqlConnection c = new MySqlConnection(connStr))
            {
                c.Open();

                Guid         g   = new Guid("32A48AC5-285A-46c6-A0D4-158E6E39729C");
                MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, ?guid)", c);
                //MySqlParameter p = new MySqlParameter();
                //p.ParameterName = "guid";
                //p.Value = Guid.NewGuid();
                cmd.Parameters.AddWithValue("guid", Guid.NewGuid());
                cmd.ExecuteNonQuery();

                cmd.CommandText = "SELECT * FROM Test";
                cmd.Parameters.Clear();
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    reader.Read();

                    object o = reader.GetValue(1);
                    Assert.IsTrue(o is Guid);

                    byte[] bytes = new byte[16];
                    long   size  = reader.GetBytes(1, 0, bytes, 0, 16);
                    Assert.AreEqual(16, size);
                }
            }
        }
Beispiel #22
0
 private void retrieveBatch(List <int> batch, byte[] buf, List <CedictEntry> entries, MySqlCommand cmdSelBinary10)
 {
     entries.Clear();
     cmdSelBinary10.Parameters["@id0"].Value = batch.Count > 0 ? batch[0] : -1;
     cmdSelBinary10.Parameters["@id1"].Value = batch.Count > 1 ? batch[1] : -1;
     cmdSelBinary10.Parameters["@id2"].Value = batch.Count > 2 ? batch[2] : -1;
     cmdSelBinary10.Parameters["@id3"].Value = batch.Count > 3 ? batch[3] : -1;
     cmdSelBinary10.Parameters["@id4"].Value = batch.Count > 4 ? batch[4] : -1;
     cmdSelBinary10.Parameters["@id5"].Value = batch.Count > 5 ? batch[5] : -1;
     cmdSelBinary10.Parameters["@id6"].Value = batch.Count > 6 ? batch[6] : -1;
     cmdSelBinary10.Parameters["@id7"].Value = batch.Count > 7 ? batch[7] : -1;
     cmdSelBinary10.Parameters["@id8"].Value = batch.Count > 8 ? batch[8] : -1;
     cmdSelBinary10.Parameters["@id9"].Value = batch.Count > 9 ? batch[9] : -1;
     for (int i = 0; i != batch.Count; ++i)
     {
         entries.Add(null);
     }
     using (MySqlDataReader rdr = cmdSelBinary10.ExecuteReader())
     {
         while (rdr.Read())
         {
             int len     = (int)rdr.GetBytes(0, 0, buf, 0, buf.Length);
             int entryId = rdr.GetInt32(1);
             using (BinReader br = new BinReader(buf, len))
             {
                 CedictEntry entry = new CedictEntry(br);
                 int         ix    = batch.IndexOf(entryId);
                 entries[ix] = entry;
             }
         }
     }
 }
Beispiel #23
0
        public override byte[] RetrieveLicenseFile(string colType, string sMAC)
        {
            string sCmd = string.Format("SELECT License FROM {0} WHERE {1}='{2}'", tablename_, colType, sMAC);

            try
            {
                MySqlCommand sqlcmd = new MySqlCommand(sCmd, sqlcon_);
                sqlcon_.Open();
                MySqlDataReader reader = sqlcmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
                while (reader.Read())
                {
                    int    maxBufferSize = 1024;
                    byte[] outByte       = new byte[maxBufferSize];
                    long   startIndex    = 0;
                    long   retval;
                    retval = reader.GetBytes(0, startIndex, outByte, 0, maxBufferSize);
                    string result  = System.Text.Encoding.UTF8.GetString(outByte, 0, (int)retval);
                    byte[] license = Convert.FromBase64String(result);
                    sqlcon_.Close();
                    UpdateDateTime(colType, sMAC);
                    return(license);
                }
            }
            catch (SystemException ex)
            {
                Trace.WriteLine(string.Format("{0}(): {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message), "ERROR");
            }
            sqlcon_.Close();

            return(null);
        }
        bool ISimulationDataPhysicsConvexStorageInterface.TryGetValue(ObjectPart.PrimitiveShape primShape, out PhysicsConvexShape shape)
        {
            using (var conn = new MySqlConnection(m_ConnectionString))
            {
                conn.Open();
                using (var cmd = new MySqlCommand("SELECT ConvexData FROM primphysics WHERE ShapeKey=@id LIMIT 1", conn))
                {
                    cmd.Parameters.AddParameter("@id", primShape.Serialization);
                    using (MySqlDataReader dbReader = cmd.ExecuteReader())
                    {
                        if (dbReader.Read())
                        {
                            shape = new PhysicsConvexShape
                            {
                                SerializedData = dbReader.GetBytes("ConvexData")
                            };
                            return(true);
                        }
                    }
                }
            }

            shape = null;
            return(false);
        }
        bool ISimulationDataPhysicsConvexStorageInterface.TryGetValue(UUID meshid, PrimitivePhysicsShapeType physicsShape, out PhysicsConvexShape shape)
        {
            using (var conn = new MySqlConnection(m_ConnectionString))
            {
                conn.Open();
                using (var cmd = new MySqlCommand("SELECT ConvexData FROM meshphysics WHERE MeshID=@id AND PhysicsShape=@stype LIMIT 1", conn))
                {
                    cmd.Parameters.AddParameter("@id", meshid);
                    cmd.Parameters.AddParameter("@stype", physicsShape);
                    using (MySqlDataReader dbReader = cmd.ExecuteReader())
                    {
                        if (dbReader.Read())
                        {
                            shape = new PhysicsConvexShape
                            {
                                SerializedData = dbReader.GetBytes("ConvexData")
                            };
                            return(true);
                        }
                    }
                }
            }

            shape = null;
            return(false);
        }
Beispiel #26
0
        public CatalogData Get()
        {
            int imageSize;

            byte[]      image;
            CatalogData cd = new CatalogData();

            cd.ColNames = new String[] { "Название продукции", "Единицы измерения", CatalogData.IMAGE_MARKER + "Изображение" };
            MySqlCommand           cmd = new MySqlCommand("SELECT p_id,p_name,p_unit,p_image,p_image,p_imgsize FROM products ORDER BY p_id ASC;", sql);
            MySqlDataReader        rd  = cmd.ExecuteReader();
            List <CatalogData.Row> rws = new List <CatalogData.Row>();

            while (rd.Read())
            {
                CatalogData.Row rw = new CatalogData.Row();
                rw.key = rd.GetInt32(0);
                //rw.imageSize = rd.GetInt32("p_imgsize");
                imageSize = rd.GetInt32("p_imgsize");
                image     = new byte[imageSize];
                if (imageSize != 0)
                {
                    rd.GetBytes(rd.GetOrdinal("p_image"), 0, image, 0, imageSize);
                }

                rw.data = new String[] { rd.GetString("p_name"), rd.GetString("p_unit"), Convert.ToBase64String(image) };
                rws.Add(rw);
            }
            rd.Close();
            cd.Rows = rws.ToArray();
            return(cd);
        }
Beispiel #27
0
        byte[] LoadFileFromDB(int id)
        {
            logger.Info("Получаем файл id={0}", id);
            string sql = String.Format("SELECT file, size FROM {0} WHERE id = @id",
                                       TableName);

            try {
                byte[]       file;
                MySqlCommand cmd = new MySqlCommand(sql, (MySqlConnection)QSMain.ConnectionDB);
                cmd.Parameters.AddWithValue("@id", id);
                using (MySqlDataReader rdr = cmd.ExecuteReader()) {
                    rdr.Read();

                    file = new byte[rdr.GetInt64("size")];
                    rdr.GetBytes(rdr.GetOrdinal("file"), 0, file, 0, rdr.GetInt32("size"));
                    TreeIter iter;
                    ListStoreWorks.SearchListStore(FilesStore, id, (int)FilesCol.id, out iter);
                    FilesStore.SetValue(iter, (int)FilesCol.file, (object)file);
                    FilesStore.SetValue(iter, (int)FilesCol.size, (object)rdr.GetInt64("size"));
                }
                logger.Info("Ок");
                return(file);
            } catch (Exception ex) {
                string mes = "Получения файла из базы!";
                logger.Error(ex, mes);
                throw new ApplicationException(mes, ex);
            }
        }
        public static byte[] GetBytesFromBlob(MySqlDataReader reader, string fieldName)
        {
            byte[] ret = null;
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] buffer = new byte[4096];
                long   pos = 0, y = 0;
                bool   exit = false;
                int    iCol = reader.GetOrdinal(fieldName);

                for (; ;)
                {
                    try
                    {
                        y = reader.GetBytes(iCol, pos, buffer, 0, buffer.Length);
                        ms.Write(buffer, 0, (int)y);
                        pos += y;

                        exit = y < buffer.Length;

                        if (exit)
                        {
                            break;
                        }
                    }
                    catch { break; }
                }
                ret = ms.ToArray();
            }
            return(ret);
        }
Beispiel #29
0
        public DnsTransaction.ResourceRecord lookup(DnsTransaction.QuestionRecord record)
        {
            uint qid = getDnsQueryId(record);

            using (MySqlCommand sql = new MySqlCommand("SELECT (ttl,data) FROM records WHERE query=@query ORDER BY cached DESC LIMIT 1", db))
            {
                sql.Parameters.AddWithValue("@query", qid);
                sql.Prepare();

                using (MySqlDataReader results = sql.ExecuteReader())
                {
                    byte[]       chunk = new byte[1024];
                    long         n     = 0;
                    long         r;
                    MemoryStream s = new MemoryStream();
                    do
                    {
                        r = results.GetBytes(1, n, chunk, 0, chunk.Length);
                        s.Write(chunk, 0, (int)r);
                    } while(r == chunk.Length);

                    return(new DnsTransaction.ResourceRecord(record, results.GetUInt32(0), s.ToArray()));
                }
            }
        }
Beispiel #30
0
        protected Endorsement(MySqlDataReader dr)
        {
            if (dr == null)
            {
                throw new ArgumentNullException("dr");
            }
            CFICertificate    = dr["CFINum"].ToString();
            StudentName       = dr["Student"].ToString();
            StudentType       = (StudentTypes)Convert.ToInt16(dr["StudentType"], CultureInfo.InvariantCulture);
            ID                = Convert.ToInt32(dr["id"], CultureInfo.InvariantCulture);
            InstructorName    = dr["CFI"].ToString();
            Date              = Convert.ToDateTime(dr["Date"], CultureInfo.InvariantCulture);
            CreationDate      = Convert.ToDateTime(util.ReadNullableField(dr, "DateCreated", DateTime.MinValue), CultureInfo.InvariantCulture);
            CFIExpirationDate = Convert.ToDateTime(dr["CFIExpiration"], CultureInfo.InvariantCulture);
            EndorsementText   = dr["Endorsement"].ToString();
            Title             = dr["Title"].ToString();
            FARReference      = dr["FARRef"].ToString();
            CFICachedName     = util.ReadNullableString(dr, "CFIFullName");

            if (!(dr["FileSize"] is DBNull))
            {
                int FileSize = Convert.ToInt32(dr["FileSize"], CultureInfo.InvariantCulture);
                DigitizedSig = new byte[FileSize];
                dr.GetBytes(dr.GetOrdinal("DigitizedSignature"), 0, DigitizedSig, 0, FileSize);
            }
            else
            {
                DigitizedSig = null;
            }
        }