public static byte[] PacketToByte(PacketBase packet)
        {
            using (var ms = new MemoryStream())
            {
                using (var bw = new BinaryWriter(ms))
                {
                    packet.WriteTo(bw);
                    var packetInfo = PacketLengthManager.GetPacketInformation((PACKET_COMMAND)packet.Command);
                    if (packet.GetType().IsSubclassOf(typeof(PacketVarSize)))
                    {
                        ((PacketVarSize)packet).SetLength(bw);
                    }

                    var send = ms.ToArray();
                    if (!IsPacketLengthSane(packet, ms))
                    {
                        if (packetInfo != null)
                        {
                            Logger.ErrorFormat("Client::Send() {0} (0x{1:X4}) wrong length {2} != {3}", ((PACKET_COMMAND)packet.Command), packet.Command, ms.Position, packetInfo);
                        }
                        else
                        {
                            Logger.ErrorFormat("Client::Send() {0} (0x{1:X4}) wrong length {2}", ((PACKET_COMMAND)packet.Command), packet.Command, ms.Position);
                        }

                        throw new ApplicationException();
                    }

                    return(send);
                }
            }
        }
        protected static bool IsPacketLengthSane(PacketBase packet, MemoryStream ms)
        {
            var info = PacketLengthManager.GetPacketInformation((PACKET_COMMAND)packet.Command);

            // Packets must have type (ushort) and sequence number (uint)
            if (ms.Length < 2)
            {
                return(false);
            }

            if (info.HasValue && ms.Length != info.Value)
            {
                return(false);
            }

            if (!info.HasValue)
            {
                var lenPos = 0;
                if (packet.GetType().IsSubclassOf(typeof(PacketVarSize)))
                {
                    lenPos = 2;
                }

                // Variable length packets must additioanlly have a length attribute (ushort)
                if (ms.Length < lenPos + 2)
                {
                    return(false);
                }

                var offset = ms.Position;
                ms.Seek(lenPos, SeekOrigin.Begin);
                var size = ms.ReadByte() | (ms.ReadByte() << 8);
                ms.Seek(offset, SeekOrigin.Begin);

                if (size != ms.Length)
                {
                    return(false);
                }
            }

            return(true);
        }