示例#1
0
        //Uses a data reader to read out a quaternion value from the database
        public static Quaternion ReadQuaternionValue(string CommandQuery, string Context = "Unknown error using reader to get quaternion value")
        {
            //Create a variable we will fill with the quaternion values when they are read from the databse
            Quaternion QuaternionValue = Quaternion.Identity;

            //Open a new connection with the base, then a datareader to get information from it
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Try using the reader to get the quaternion values that were looking for
            try
            {
                QuaternionValue.X = Convert.ToSingle(Reader["XRotation"]);
                QuaternionValue.Y = Convert.ToSingle(Reader["YRotation"]);
                QuaternionValue.Z = Convert.ToSingle(Reader["ZRotation"]);
                QuaternionValue.W = Convert.ToSingle(Reader["WRotation"]);
            }
            catch (MySqlException Exception) { MessageLog.Error(Exception, Context); }

            //Close the data reader, database connection then return the final quaternion values
            Reader.Close();
            Connection.Close();
            return(QuaternionValue);
        }
示例#2
0
        //Creates a new command used for executing on the SQL Database Server
        private static MySqlCommand CreateCommand(string CommandQuery, MySqlConnection DatabaseConnection, string Context)
        {
            MySqlCommand NewCommand = null;

            try { NewCommand = new MySqlCommand(CommandQuery, DatabaseConnection); }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error creating new command: " + Context); }
            return(NewCommand);
        }
示例#3
0
        //Uses the given Query to create a new command and run it on the database
        public static void ExecuteNonQuery(string CommandQuery, string Context = "Unknown error executing non query command")
        {
            //Open a new connection and create a new command
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);

            //Execute the command if it was created successfully
            if (Command != null && Command.Connection != null)
            {
                try { Command.ExecuteNonQuery(); }
                catch (MySqlException Exception) { MessageLog.Error(Exception, "Error executing non query command: " + Context); }
            }

            //Close the connection
            Connection.Close();
        }
示例#4
0
        public void TransmitPackets(bool Transmit)
        {
            //Copy the current outgoing queue into a new array and reset the queue
            Dictionary <int, NetworkPacket> TransmissionQueue = new Dictionary <int, NetworkPacket>(PacketQueue);

            PacketQueue.Clear();

            //All packet data will be combined into this string
            string PacketData = "";

            //Append data of each packet onto the send
            if (!PacketsToResend)
            {
                foreach (KeyValuePair <int, NetworkPacket> Packet in TransmissionQueue)
                {
                    PacketData += Packet.Value.PacketData;
                }
            }
            //Otherwise we need to append the data of all the missing packets
            else
            {
                for (int i = ResendFrom; i < LastPacketRecieved + 1; i++)
                {
                    if (PacketHistory.ContainsKey(i))
                    {
                        PacketData += PacketHistory[i].PacketData;
                    }
                }
                PacketsToResend = false;
            }

            if (PacketData != "" && Transmit)
            {
                byte[] PacketBytes = GetFrameFromString(PacketData);
                int    PacketSize  = Encoding.UTF8.GetString(PacketBytes).Length;
                try { DataStream.BeginWrite(PacketBytes, 0, PacketSize, null, null); }
                catch (IOException Exception)
                {
                    MessageLog.Error(Exception, "Error transmitting packets to client");
                    ConnectionDead = true;
                }
            }
        }
示例#5
0
        //Checks if some table in the database contains a specific row that we are searching for
        public static bool ExecuteRowCheck(string CommandQuery, string Context = "Unknown error executing row check command")
        {
            //Create variable we will flag if the row check is successful
            bool RowCheck = false;

            //Open a new connection, create a new command and use that to open a new datareader
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to check for the rows that were looking for
            try { RowCheck = Reader.HasRows; }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error using reader to perform row check: " + Context); }

            //Close the reader and the sql connection, then return the boolean value
            Reader.Close();
            Connection.Close();
            return(RowCheck);
        }
示例#6
0
        //Uses a data reader to read out a string value from the database
        public static string ReadStringValue(string CommandQuery, string StringName, string Context = "Unknown error using reader to get string value")
        {
            //Create variable we will fill with the string value when its read from the database
            string StringValue = "";

            //Open a new connection, create a new command and then use that to open a new datareader
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to read out the string value that were looking for
            try { StringValue = Reader[StringName].ToString(); }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error using data reader to get string value: " + Context); }

            //Close the data reader and the SQL connection, then return the string value
            Reader.Close();
            Connection.Close();
            return(StringValue);
        }
示例#7
0
        //Uses a data reader to read out a boolean value from the database
        public static bool ReadBooleanValue(string CommandQuery, string BooleanName, string Context = "Unknown error using reader to get boolean value")
        {
            //Create variable we will fill with the boolean value when its read from the database
            bool BooleanValue = false;

            //Open a new connection, create a new command then use that to open a new datareader
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to read out the boolean value that were looking for
            try { BooleanValue = Convert.ToBoolean(Reader[BooleanName]); }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error using data reader to get boolean value: " + Context); }

            //Close the data reader and the SQL connection, then return the boolean value
            Reader.Close();
            Connection.Close();
            return(BooleanValue);
        }
示例#8
0
        //Uses a data reader object to read out a floating point value from the database
        public static float ReadFloatValue(string CommandQuery, string FloatName, string Context = "Unknown error using data reader to get float value")
        {
            //Create local variable to store the float value
            float FloatValue = 0f;

            //Open a new connection, create a new command then use that to open a new datareader object
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to get the float value that were looking for
            try { FloatValue = Convert.ToSingle(Reader[FloatName]); }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error using data reader to get floating point value: " + Context); }

            //Close the reader/SQL connection then return the float value
            Reader.Close();
            Connection.Close();
            return(FloatValue);
        }
示例#9
0
        //Uses a data reader to read out an integer value from the database
        public static int ReadIntegerValue(string CommandQuery, string IntegerName, string Context = "Unknown error using data reader to get integer value")
        {
            //Create variable we will fill with the integer value when its read from the database
            int IntegerValue = 0;

            //Open a new connection, create a new command then use that to open a new datareader object
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to read out the integer value that were looking for
            try { IntegerValue = Convert.ToInt32(Reader[IntegerName]); }
            catch (MySqlException Exception) { MessageLog.Error(Exception, "Error using data reader to get integer value: " + Context); }

            //Close the reader and the SQL connection, then return the integer value
            Reader.Close();
            Connection.Close();
            return(IntegerValue);
        }
示例#10
0
        //Reads out an integer value from the database
        public static int ExecuteScalar(string CommandQuery, string Context = "Unknown error executing scalar value check command")
        {
            //Create variable we will fill with the scalar value when its read from the database
            int ScalarValue = 0;

            //Open a new connection, create a new command
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);

            //Execute the command to read the scalar value if the command was created successfully
            if (Command != null)
            {
                try { ScalarValue = Convert.ToInt32(Command.ExecuteScalar()); }
                catch (MySqlException Exception) { MessageLog.Error(Exception, Context); }
            }

            //Close the database connection and return the final scalar value we are left with
            Connection.Close();
            return(ScalarValue);
        }
示例#11
0
        //Uses a data reader to read out a vector3 value from the database
        public static Vector3 ReadVectorValue(string CommandQuery, string Context = "Unknown error using reader to get vector value")
        {
            //Create variable we will fill with the vector values when they are read from the database
            Vector3 VectorValue = new Vector3();

            //Open a new connection, create a new command then use that to open a new datareader
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Use the reader to read out the vector values that were looking for
            try
            {
                VectorValue.X = Convert.ToSingle(Reader["XPosition"]);
                VectorValue.Y = Convert.ToSingle(Reader["YPosition"]);
                VectorValue.Z = Convert.ToSingle(Reader["ZPosition"]);
            }
            catch (MySqlException Exception) { MessageLog.Error(Exception, Context); }

            //Close the data reader and the SQL connection, then return the vector value
            Reader.Close();
            Connection.Close();
            return(VectorValue);
        }
示例#12
0
        /// <summary>
        /// Triggers after completion of asynchronous datastream reading has completed transmitting data
        /// </summary>
        /// <param name="Result">Represents the status of an asynchronous operation</param>
        private void ReadPacket(IAsyncResult Result)
        {
            //Read in the size of the payload data, making sure the connection is still opened
            int PacketSize = -1;

            try { PacketSize = DataStream.EndRead(Result); }
            //Print an error message, flag the client as dead and exit the function if any exception occurs
            catch (IOException Exception)
            {
                MessageLog.Error(Exception, "Error reading packet size, connection no longer open.");
                ConnectionDead = true;
                return;
            }

            //Copy the data buffer over into a new array and reset the buffer array for reading in the next packet
            byte[] PacketBuffer = new byte[PacketSize];
            Array.Copy(DataBuffer, PacketBuffer, PacketSize);
            DataBuffer = new byte[Connection.Available];
            //Immediately start reading packets again from the client back into the data buffer, making sure the connection is still open
            try { DataStream.BeginRead(DataBuffer, 0, DataBuffer.Length, ReadPacket, null); }
            //Print an error, flag the client as dead and exit the function if any exception occurs
            catch (IOException Exception)
            {
                MessageLog.Error(Exception, "Error registering packet reader function, client connection no longer open.");
                ConnectionDead = true;
                return;
            }

            //If the connection is new then complete the handshake and upgrade the connection to websockets
            if (!ConnectionUpgraded)
            {
                UpgradeConnection(PacketBuffer);
            }
            //Otherwise we need to extract the packet data from the buffer and decode it so we can read and process the messages within
            else if (PacketSize > 0)
            {
                //Visit https://tools.ietf.org/html/rfc6455#section-5.2 for more information on how this decoding works
                //Lets first extract the data from the first byte
                byte   FirstByte = PacketBuffer[0];
                bool   FIN       = DataExtractor.ReadBit(FirstByte, 0); //Value of 1 indicates if this is the final fragment of the message, this first fragment MAY also be the final fragment
                bool   RSV1      = DataExtractor.ReadBit(FirstByte, 1); //Set to 0 unless an extension is negotatied that defines meanings for non-zero values. Unexpected non-zero values means we should close down the connection.
                bool   RSV2      = DataExtractor.ReadBit(FirstByte, 2);
                bool   RSV3      = DataExtractor.ReadBit(FirstByte, 3);
                bool[] OpCode    = DataExtractor.ReadBits(FirstByte, 4, 7);

                //Extracting the second byte from the packet buffer
                byte SecondByte = PacketBuffer[1];
                bool MASK       = DataExtractor.ReadBit(SecondByte, 0);

                //Before we go any further we need to figure out the size of the payload data, as this may effect where we read the rest of the data from
                //Converting the 2nd byte to a binary string, then converting bits 1-7 to decimal gives us the first possible length value of the payload data
                string SecondByteBinary = BinaryConverter.ByteToBinaryString(PacketBuffer[1]);
                string PayloadBinary    = SecondByteBinary.Substring(1, 7);
                int    PayloadLength    = BinaryConverter.BinaryStringToDecimal(PayloadBinary);

                //Byte indices where we will begin reading in the decoding mask and payload data later on, these will be updated if we needed to read extra bytes to find out the payload length
                int DecodingMaskIndex = 2;
                int PayloadDataIndex  = 6;

                //PayloadLength between 0-125 represents the actual length value
                //With a length equal to 126, we read bytes 2-3 to find the length value
                if (PayloadLength == 126)
                {
                    //Bytes 2 and 3 interpreted as 16bit unsigned integer give the PayloadLength
                    byte[] LengthBytes = DataExtractor.ReadBytes(PacketBuffer, 2, 3);
                    PayloadBinary = BinaryConverter.ByteArrayToBinaryString(LengthBytes);
                    PayloadLength = BinaryConverter.BinaryStringToDecimal(PayloadBinary);
                    //Increment the DecodingMask and PayloadData indices by 2, as 3,4 contained the payload length
                    DecodingMaskIndex += 2;
                    PayloadDataIndex  += 2;
                }
                //Write a length equal to 127, we read bytes 2-9 to find the length value
                else if (PayloadLength == 127)
                {
                    //Bytes 2-9 interpreted as a 64bit unsigned integer give the PayloadLength
                    byte[] LengthBytes = DataExtractor.ReadBytes(PacketBuffer, 2, 9);
                    PayloadBinary      = BinaryConverter.ByteArrayToBinaryString(LengthBytes);
                    PayloadLength      = BinaryConverter.BinaryStringToDecimal(PayloadBinary);
                    DecodingMaskIndex += 8;
                    PayloadDataIndex  += 8;
                }

                //Extract the decoding mask bytes from the packet buffer
                byte[] DecodingMask = new byte[4] {
                    PacketBuffer[DecodingMaskIndex], PacketBuffer[DecodingMaskIndex + 1], PacketBuffer[DecodingMaskIndex + 2], PacketBuffer[DecodingMaskIndex + 3]
                };

                //Extract the payload data from the packet buffer, using the mask to decode each byte as we extract it from the packet buffer
                byte[] PayloadData = new byte[PayloadLength];
                for (int i = 0; i < PayloadLength; i++)
                {
                    PayloadData[i] = (byte)(PacketBuffer[PayloadDataIndex + i] ^ DecodingMask[i % 4]);
                }

                //Convert the PayloadData array into an ASCII string
                string FinalMessage = Encoding.ASCII.GetString(PayloadData);

                //If the FinalMessage value comes through as "\u0003?" then the connection has been closed from the client side, so we need to set
                //them as dead so they get cleaned up by the simulation
                if (FinalMessage == "\u0003?")
                {
                    ConnectionDead = true;
                }
                //Otherwise we just pass the message onto the packet handler as normal so it can be processed accordingly
                else
                {
                    PacketHandler.ReadClientPacket(ClientID, FinalMessage);
                }
            }
        }