Add files via upload

This commit is contained in:
Bluzume 2020-09-30 18:23:19 +13:00 committed by GitHub
parent 14ff669234
commit b0652c2c83
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 2422 additions and 2323 deletions

View file

@ -1,89 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Authentication
{
public static string DecryptLogin(string encpass)
{
string decrypt = "";
string ROTPOOL = "bl7Jgk61IZdnY mfDN5zjM2XLqTCty4WSEoKR3BFVQsaUhHOAx0rPwp9uc8iGve";
string POSPOOL = "DQc3uxiGsKZatMmOS5qYveN71zoPTk8yU0H2w9VjprBXWn l4FJd6IRbhgACfEL";
string ROTPOOL2 = "evGi8cu9pwPr0xAOHhUasQVFB3RKoESW4ytCTqLX2Mjz5NDfm YndZI16kgJ7lb";
int i = 0;
int ii = 0;
while (i < encpass.Length)
{
int ROT = ROTPOOL.IndexOf(encpass[i].ToString());
int POS = POSPOOL.IndexOf(encpass[i + 1].ToString());
POS -= (ROT + ii);
if (POS < 0)
{
POS = (POS / -1) - 1;
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL2[POS];
}
else
{
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL[POS];
}
i += 2;
ii += 1;
}
return decrypt.Replace(" ", "");
}
public static byte[] HashAndSalt(string plaintext, byte[] salt)
{
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
SHA512 sha512 = new SHA512Managed();
byte[] hash = sha512.ComputeHash(plaintextBytes);
for (int i = 0; i < hash.Length; i++)
{
hash[i] ^= salt[i];
}
byte[] finalHash = sha512.ComputeHash(hash);
return finalHash;
}
public static bool CheckPassword(string username, string password)
{
if(Database.CheckUserExist(username))
{
byte[] expectedPassword = Database.GetPasswordHash(username);
byte[] salt = Database.GetPasswordSalt(username);
byte[] hashedPassword = HashAndSalt(password, salt);
if (Enumerable.SequenceEqual(expectedPassword, hashedPassword))
return true;
}
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Authentication
{
public static string DecryptLogin(string encpass)
{
string decrypt = "";
string ROTPOOL = "bl7Jgk61IZdnY mfDN5zjM2XLqTCty4WSEoKR3BFVQsaUhHOAx0rPwp9uc8iGve";
string POSPOOL = "DQc3uxiGsKZatMmOS5qYveN71zoPTk8yU0H2w9VjprBXWn l4FJd6IRbhgACfEL";
string ROTPOOL2 = "evGi8cu9pwPr0xAOHhUasQVFB3RKoESW4ytCTqLX2Mjz5NDfm YndZI16kgJ7lb";
int i = 0;
int ii = 0;
while (i < encpass.Length)
{
int ROT = ROTPOOL.IndexOf(encpass[i].ToString());
int POS = POSPOOL.IndexOf(encpass[i + 1].ToString());
POS -= (ROT + ii);
if (POS < 0)
{
POS = (POS / -1) - 1;
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL2[POS];
}
else
{
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL[POS];
}
i += 2;
ii += 1;
}
return decrypt.Replace(" ", "");
}
public static byte[] HashAndSalt(string plaintext, byte[] salt)
{
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
SHA512 sha512 = new SHA512Managed();
byte[] hash = sha512.ComputeHash(plaintextBytes);
for (int i = 0; i < hash.Length; i++)
{
hash[i] ^= salt[i];
}
byte[] finalHash = sha512.ComputeHash(hash);
return finalHash;
}
public static bool CheckPassword(string username, string password)
{
if(Database.CheckUserExist(username))
{
byte[] expectedPassword = Database.GetPasswordHash(username);
byte[] salt = Database.GetPasswordSalt(username);
byte[] hashedPassword = HashAndSalt(password, salt);
if (Enumerable.SequenceEqual(expectedPassword, hashedPassword))
return true;
}
return false;
}
}
}

View file

@ -1,134 +1,137 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Client
{
public Socket ClientSocket;
public string RemoteIp;
public bool LoggedIn = false;
public User LoggedinUser;
private Thread recvPackets;
public void Login(int id)
{
LoggedinUser = new User(id);
LoggedIn = true;
}
private void receivePackets()
{
// HI1 Packets are terminates by 0x00 so we have to read until we receive that terminator
MemoryStream ms = new MemoryStream();
while(ClientSocket.Connected)
{
try
{
if (ClientSocket.Available >= 1)
{
byte[] buffer = new byte[ClientSocket.Available];
ClientSocket.Receive(buffer);
foreach (Byte b in buffer)
{
ms.WriteByte(b);
if (b == 0x00)
{
ms.Seek(0x00, SeekOrigin.Begin);
byte[] fullPacket = ms.ToArray();
parsePackets(fullPacket);
ms.Close();
ms = new MemoryStream();
}
}
}
}
catch(SocketException e)
{
Logger.ErrorPrint("Socket exception occured: " + e.Message +" and so it was disconnected.");
Disconnect();
break;
}
}
}
private void parsePackets(byte[] Packet)
{
if (Packet.Length < 1)
{
Logger.ErrorPrint("Received an invalid packet (size: "+Packet.Length+")");
}
byte identifier = Packet[0];
if (!LoggedIn) // Must be either login or policy-file-request
{
if (Encoding.UTF8.GetString(Packet).StartsWith("<policy-file-request/>")) // Policy File Request
{
Server.OnCrossdomainPolicyRequest(this);
}
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
Server.OnLoginRequest(this, Packet);
break;
}
}
else
{
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
Server.OnUserInfoRequest(this, Packet);
break;
case PacketBuilder.PACKET_MOVE:
Server.OnMovementPacket(this, Packet);
break;
default:
Logger.ErrorPrint("Unimplemented Packet: " + BitConverter.ToString(Packet).Replace('-', ' '));
break;
}
}
}
public void Disconnect()
{
Server.ConnectedClients.Remove(this);
ClientSocket.Dispose();
}
public void SendPacket(byte[] PacketData)
{
ClientSocket.Send(PacketData);
}
public Client(Socket clientSocket)
{
ClientSocket = clientSocket;
RemoteIp = clientSocket.RemoteEndPoint.ToString();
Logger.DebugPrint("Client connected @ " + RemoteIp);
recvPackets = new Thread(() =>
{
receivePackets();
});
recvPackets.Start();
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Client
{
public Socket ClientSocket;
public string RemoteIp;
public bool LoggedIn = false;
public User LoggedinUser;
private Thread recvPackets;
public void Login(int id)
{
LoggedinUser = new User(id);
LoggedIn = true;
}
private void receivePackets()
{
// HI1 Packets are terminates by 0x00 so we have to read until we receive that terminator
MemoryStream ms = new MemoryStream();
while(ClientSocket.Connected)
{
try
{
if (ClientSocket.Available >= 1)
{
byte[] buffer = new byte[ClientSocket.Available];
ClientSocket.Receive(buffer);
foreach (Byte b in buffer)
{
ms.WriteByte(b);
if (b == 0x00)
{
ms.Seek(0x00, SeekOrigin.Begin);
byte[] fullPacket = ms.ToArray();
parsePackets(fullPacket);
ms.Close();
ms = new MemoryStream();
}
}
}
}
catch(SocketException e)
{
Logger.ErrorPrint("Socket exception occured: " + e.Message +" and so it was disconnected.");
Disconnect();
break;
}
}
}
private void parsePackets(byte[] Packet)
{
if (Packet.Length < 1)
{
Logger.ErrorPrint("Received an invalid packet (size: "+Packet.Length+")");
}
byte identifier = Packet[0];
if (!LoggedIn) // Must be either login or policy-file-request
{
if (Encoding.UTF8.GetString(Packet).StartsWith("<policy-file-request/>")) // Policy File Request
{
Server.OnCrossdomainPolicyRequest(this);
}
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
Server.OnLoginRequest(this, Packet);
break;
}
}
else
{
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
Server.OnUserInfoRequest(this, Packet);
break;
case PacketBuilder.PACKET_MOVE:
Server.OnMovementPacket(this, Packet);
break;
default:
Logger.ErrorPrint("Unimplemented Packet: " + BitConverter.ToString(Packet).Replace('-', ' '));
break;
}
}
}
public void Disconnect()
{
Logger.DebugPrint(ClientSocket.RemoteEndPoint + " has Disconnected.");
LoggedIn = false;
LoggedinUser = null;
Server.ConnectedClients.Remove(this);
ClientSocket.Dispose();
}
public void SendPacket(byte[] PacketData)
{
ClientSocket.Send(PacketData);
}
public Client(Socket clientSocket)
{
ClientSocket = clientSocket;
RemoteIp = clientSocket.RemoteEndPoint.ToString();
Logger.DebugPrint("Client connected @ " + RemoteIp);
recvPackets = new Thread(() =>
{
receivePackets();
});
recvPackets.Start();
}
}
}

View file

@ -1,107 +1,103 @@
using Horse_Isle_Server.Properties;
using System;
using System.IO;
namespace Horse_Isle_Server
{
class ConfigReader
{
public static int Port;
public static string BindIP;
public static string DatabaseIP;
public static string DatabaseUsername;
public static string DatabaseName;
public static string DatabasePassword;
public static int DatabasePort;
public static string Motd;
public static string MapFile;
public static string OverlayMapFile;
public static string GameDataFile;
public static string CrossDomainPolicyFile;
public static bool Debug;
private static string ConfigurationFileName = "server.properties";
public static void OpenConfig()
{
if (!File.Exists(ConfigurationFileName))
{
Logger.ErrorPrint(ConfigurationFileName+" not found! writing default.");
File.WriteAllText(ConfigurationFileName,Resources.DefaultServerProperties);
}
string[] configFile = File.ReadAllLines(ConfigurationFileName);
foreach (string setting in configFile)
{
/*
* Avoid crashing.
*/
if (setting.Length < 1)
continue;
if (setting[0] == '#')
continue;
if (!setting.Contains("="))
continue;
string[] dataPair = setting.Split('=');
string key = dataPair[0];
string data = dataPair[1];
/*
* Parse configuration file
*/
switch (key)
{
case "port":
Port = int.Parse(data);
break;
case "ip":
BindIP = data;
break;
case "db_ip":
DatabaseIP = data;
break;
case "db_username":
DatabaseUsername = data;
break;
case "db_password":
DatabasePassword = data;
break;
case "db_name":
DatabaseName = data;
break;
case "db_port":
DatabasePort = int.Parse(data);
break;
case "map":
MapFile = data;
break;
case "motd":
Motd = data;
break;
case "gamedata":
GameDataFile = data;
break;
case "overlaymap":
OverlayMapFile = data;
break;
case "crossdomain":
CrossDomainPolicyFile = data;
break;
case "debug":
Debug = data == "true";
break;
}
}
}
}
}
using Horse_Isle_Server.Properties;
using System;
using System.IO;
namespace Horse_Isle_Server
{
class ConfigReader
{
public static int Port;
public static string BindIP;
public static string DatabaseIP;
public static string DatabaseUsername;
public static string DatabaseName;
public static string DatabasePassword;
public static int DatabasePort;
public static string Motd;
public static string MapFile;
public static string GameDataFile;
public static string CrossDomainPolicyFile;
public static bool Debug;
private static string ConfigurationFileName = "server.properties";
public static void OpenConfig()
{
if (!File.Exists(ConfigurationFileName))
{
Logger.ErrorPrint(ConfigurationFileName+" not found! writing default.");
File.WriteAllText(ConfigurationFileName,Resources.DefaultServerProperties);
}
string[] configFile = File.ReadAllLines(ConfigurationFileName);
foreach (string setting in configFile)
{
/*
* Avoid crashing.
*/
if (setting.Length < 1)
continue;
if (setting[0] == '#')
continue;
if (!setting.Contains("="))
continue;
string[] dataPair = setting.Split('=');
string key = dataPair[0];
string data = dataPair[1];
/*
* Parse configuration file
*/
switch (key)
{
case "port":
Port = int.Parse(data);
break;
case "ip":
BindIP = data;
break;
case "db_ip":
DatabaseIP = data;
break;
case "db_username":
DatabaseUsername = data;
break;
case "db_password":
DatabasePassword = data;
break;
case "db_name":
DatabaseName = data;
break;
case "db_port":
DatabasePort = int.Parse(data);
break;
case "map":
MapFile = data;
break;
case "motd":
Motd = data;
break;
case "gamedata":
GameDataFile = data;
break;
case "crossdomain":
CrossDomainPolicyFile = data;
break;
case "debug":
Debug = data == "true";
break;
}
}
}
}
}

View file

@ -1,38 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Converters
{
// Thanks Stackoverflow (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array)
private static int getHexVal(char hex)
{
int val = (int)hex;
//For uppercase A-F letters:
//return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
public static byte[] StringToByteArray(string hex)
{
if (hex.Length % 2 == 1)
throw new ArgumentException("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((getHexVal(hex[i << 1]) << 4) + (getHexVal(hex[(i << 1) + 1])));
}
return arr;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Converters
{
// Thanks Stackoverflow (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array)
private static int getHexVal(char hex)
{
int val = (int)hex;
//For uppercase A-F letters:
//return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
public static byte[] StringToByteArray(string hex)
{
if (hex.Length % 2 == 1)
throw new ArgumentException("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((getHexVal(hex[i << 1]) << 4) + (getHexVal(hex[(i << 1) + 1])));
}
return arr;
}
}
}

View file

@ -1,34 +1,34 @@
using Horse_Isle_Server.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class CrossDomainPolicy
{
public static byte[] GetPolicy()
{
if (!File.Exists(ConfigReader.CrossDomainPolicyFile)) {
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] Cross-Domain-Policy file not found, using default");
File.WriteAllText(ConfigReader.CrossDomainPolicyFile, Resources.DefaultCrossDomain);
}
MemoryStream ms = new MemoryStream();
byte[] policyFileBytes = File.ReadAllBytes(ConfigReader.CrossDomainPolicyFile);
ms.Write(policyFileBytes, 0x00, policyFileBytes.Length);
ms.WriteByte(0x00);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] policyFileData = ms.ToArray();
ms.Close();
return policyFileData;
}
}
}
using Horse_Isle_Server.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class CrossDomainPolicy
{
public static byte[] GetPolicy()
{
if (!File.Exists(ConfigReader.CrossDomainPolicyFile)) {
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] Cross-Domain-Policy file not found, using default");
File.WriteAllText(ConfigReader.CrossDomainPolicyFile, Resources.DefaultCrossDomain);
}
MemoryStream ms = new MemoryStream();
byte[] policyFileBytes = File.ReadAllBytes(ConfigReader.CrossDomainPolicyFile);
ms.Write(policyFileBytes, 0x00, policyFileBytes.Length);
ms.WriteByte(0x00);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] policyFileData = ms.ToArray();
ms.Close();
return policyFileData;
}
}
}

View file

@ -1,498 +1,498 @@
using System;
using System.Collections.Generic;
using MySqlConnector;
namespace Horse_Isle_Server
{
class Database
{
public static MySqlConnection db;
public static void OpenDatabase()
{
db = new MySqlConnection("server=" + ConfigReader.DatabaseIP + ";user=" + ConfigReader.DatabaseUsername + ";password=" + ConfigReader.DatabasePassword+";database="+ConfigReader.DatabaseName);
db.Open();
string UserTable = "CREATE TABLE Users(Id INT, Username TEXT(16),Email TEXT(128),Country TEXT(128),SecurityQuestion Text(128),SecurityAnswerHash TEXT(128),Age INT,PassHash TEXT(128), Salt TEXT(128),Gender TEXT(16), Admin TEXT(3), Moderator TEXT(3))";
string ExtTable = "CREATE TABLE UserExt(Id INT, X INT, Y INT, Money INT, BankBalance BIGINT,ProfilePage Text(1028), CharId INT)";
string MailTable = "CREATE TABLE Mailbox(IdTo INT, PlayerFrom TEXT(16),Subject TEXT(128), Message Text(1028), TimeSent INT)";
string WorldTable = "CREATE TABLE World(TimeStarted INT, Weather TEXT(64))";
string DroppedTable = "CREATE TABLE DroppedItems(X INT, Y INT, ItemID INT)";
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = UserTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e) {
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = ExtTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = MailTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = DroppedTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = WorldTable;
sqlCommand.ExecuteNonQuery();
int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "INSERT INTO World VALUES(@unix,'SUNNY')";
sqlCommand.Parameters.AddWithValue("@unix", epoch);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
}
public static int GetServerCreationTime()
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT TimeStarted FROM World";
int creationTime = Convert.ToInt32(sqlCommand.ExecuteScalar());
return creationTime;
}
public static string GetWorldWeather()
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Weather FROM World";
string Weather = sqlCommand.ExecuteScalar().ToString();
return Weather;
}
public static void SetWorldWeather(string Weather)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE World SET Weather=@weather";
sqlCommand.Parameters.AddWithValue("@weather", Weather);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static byte[] GetPasswordSalt(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Salt FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string expectedHash = sqlCommand.ExecuteScalar().ToString();
return Converters.StringToByteArray(expectedHash);
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static int CheckMailcount(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Mailbox WHERE IdTo=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count;
}
public static void AddMail(int toId, string fromName, string subject, string message)
{
MySqlCommand sqlCommand = db.CreateCommand();
int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
sqlCommand.CommandText = "INSERT INTO Mailbox VALUES(@toId,@from,@subject,@message,@time)";
sqlCommand.Parameters.AddWithValue("@toId", toId);
sqlCommand.Parameters.AddWithValue("@from", fromName);
sqlCommand.Parameters.AddWithValue("@subject", subject);
sqlCommand.Parameters.AddWithValue("@mesasge", message);
sqlCommand.Parameters.AddWithValue("@time", epoch);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static bool CheckUserExist(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserExist(string username)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserExtExists(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserIsModerator(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Moderator FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string modStr = sqlCommand.ExecuteScalar().ToString();
return modStr == "YES";
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static bool CheckUserIsAdmin(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Admin FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string adminStr = sqlCommand.ExecuteScalar().ToString();
return adminStr == "YES";
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static void CreateUserExt(int id)
{
if (CheckUserExtExists(id)) // user allready exists!
throw new Exception("Userid " + id + " Allready in userext.");
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "INSERT INTO UserExt VALUES(@id,@x,@y,0,0,'',5)";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Parameters.AddWithValue("@x", Gamedata.NewUserStartX);
sqlCommand.Parameters.AddWithValue("@y", Gamedata.NewUserStartY);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static int GetUserid(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Id FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
int userId = Convert.ToInt32(sqlCommand.ExecuteScalar());
return userId;
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static int GetPlayerCharId(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT CharId FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int CharId = Convert.ToInt32(sqlCommand.ExecuteScalar());
return CharId;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerCharId(int charid, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET CharId=@charId WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@charId", charid);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerX(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT X FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int X = Convert.ToInt32(sqlCommand.ExecuteScalar());
return X;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerX(int x, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET X=@x WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@x", x);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerY(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Y FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int Y = Convert.ToInt32(sqlCommand.ExecuteScalar());
return Y;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerY(int y, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET Y=@y WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@y", y);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static void SetPlayerMoney(int money, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET Money=@money WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@money", money);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerMoney(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Money FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int Money = Convert.ToInt32(sqlCommand.ExecuteScalar());
return Money;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static int GetPlayerBankMoney(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT BankBalance FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int BankMoney = Convert.ToInt32(sqlCommand.ExecuteScalar());
return BankMoney;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerBankMoney(int bankMoney, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET BankBalance=@bankMoney WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@bankMoney", bankMoney);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static void SetPlayerProfile(string profilePage, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET ProfilePage=@profilePage WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@profilePage", profilePage);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static string GetPlayerProfile(int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT ProfilePage FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
string profilePage = sqlCommand.ExecuteScalar().ToString();
return profilePage;
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static string GetUsername(int userId)
{
if(CheckUserExist(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Username FROM Users WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
string username = sqlCommand.ExecuteScalar().ToString();
return username;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static byte[] GetPasswordHash(string username)
{
if(CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT PassHash FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string expectedHash = sqlCommand.ExecuteScalar().ToString();
return Converters.StringToByteArray(expectedHash);
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
}
using System;
using System.Collections.Generic;
using MySqlConnector;
namespace Horse_Isle_Server
{
class Database
{
public static MySqlConnection db;
public static void OpenDatabase()
{
db = new MySqlConnection("server=" + ConfigReader.DatabaseIP + ";user=" + ConfigReader.DatabaseUsername + ";password=" + ConfigReader.DatabasePassword+";database="+ConfigReader.DatabaseName);
db.Open();
string UserTable = "CREATE TABLE Users(Id INT, Username TEXT(16),Email TEXT(128),Country TEXT(128),SecurityQuestion Text(128),SecurityAnswerHash TEXT(128),Age INT,PassHash TEXT(128), Salt TEXT(128),Gender TEXT(16), Admin TEXT(3), Moderator TEXT(3))";
string ExtTable = "CREATE TABLE UserExt(Id INT, X INT, Y INT, Money INT, BankBalance BIGINT,ProfilePage Text(1028), CharId INT)";
string MailTable = "CREATE TABLE Mailbox(IdTo INT, PlayerFrom TEXT(16),Subject TEXT(128), Message Text(1028), TimeSent INT)";
string WorldTable = "CREATE TABLE World(TimeStarted INT, Weather TEXT(64))";
string DroppedTable = "CREATE TABLE DroppedItems(X INT, Y INT, ItemID INT)";
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = UserTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e) {
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = ExtTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = MailTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = DroppedTable;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
try
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = WorldTable;
sqlCommand.ExecuteNonQuery();
int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "INSERT INTO World VALUES(@unix,'SUNNY')";
sqlCommand.Parameters.AddWithValue("@unix", epoch);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Logger.WarnPrint(e.Message);
};
}
public static int GetServerCreationTime()
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT TimeStarted FROM World";
int creationTime = Convert.ToInt32(sqlCommand.ExecuteScalar());
return creationTime;
}
public static string GetWorldWeather()
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Weather FROM World";
string Weather = sqlCommand.ExecuteScalar().ToString();
return Weather;
}
public static void SetWorldWeather(string Weather)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE World SET Weather=@weather";
sqlCommand.Parameters.AddWithValue("@weather", Weather);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static byte[] GetPasswordSalt(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Salt FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string expectedHash = sqlCommand.ExecuteScalar().ToString();
return Converters.StringToByteArray(expectedHash);
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static int CheckMailcount(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Mailbox WHERE IdTo=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count;
}
public static void AddMail(int toId, string fromName, string subject, string message)
{
MySqlCommand sqlCommand = db.CreateCommand();
int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
sqlCommand.CommandText = "INSERT INTO Mailbox VALUES(@toId,@from,@subject,@message,@time)";
sqlCommand.Parameters.AddWithValue("@toId", toId);
sqlCommand.Parameters.AddWithValue("@from", fromName);
sqlCommand.Parameters.AddWithValue("@subject", subject);
sqlCommand.Parameters.AddWithValue("@mesasge", message);
sqlCommand.Parameters.AddWithValue("@time", epoch);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static bool CheckUserExist(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserExist(string username)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserExtExists(int id)
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT COUNT(1) FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar());
return count >= 1;
}
public static bool CheckUserIsModerator(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Moderator FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string modStr = sqlCommand.ExecuteScalar().ToString();
return modStr == "YES";
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static bool CheckUserIsAdmin(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Admin FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string adminStr = sqlCommand.ExecuteScalar().ToString();
return adminStr == "YES";
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static void CreateUserExt(int id)
{
if (CheckUserExtExists(id)) // user allready exists!
throw new Exception("Userid " + id + " Allready in userext.");
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "INSERT INTO UserExt VALUES(@id,@x,@y,0,0,'',0)";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Parameters.AddWithValue("@x", Map.NewUserStartX);
sqlCommand.Parameters.AddWithValue("@y", Map.NewUserStartY);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
public static int GetUserid(string username)
{
if (CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Id FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
int userId = Convert.ToInt32(sqlCommand.ExecuteScalar());
return userId;
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
public static int GetPlayerCharId(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT CharId FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int CharId = Convert.ToInt32(sqlCommand.ExecuteScalar());
return CharId;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerCharId(int charid, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET CharId=@charId WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@charId", charid);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerX(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT X FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int X = Convert.ToInt32(sqlCommand.ExecuteScalar());
return X;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerX(int x, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET X=@x WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@x", x);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerY(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Y FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int Y = Convert.ToInt32(sqlCommand.ExecuteScalar());
return Y;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerY(int y, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET Y=@y WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@y", y);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static void SetPlayerMoney(int money, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET Money=@money WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@money", money);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static int GetPlayerMoney(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Money FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int Money = Convert.ToInt32(sqlCommand.ExecuteScalar());
return Money;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static int GetPlayerBankMoney(int userId)
{
if (CheckUserExtExists(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT BankBalance FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
int BankMoney = Convert.ToInt32(sqlCommand.ExecuteScalar());
return BankMoney;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static void SetPlayerBankMoney(int bankMoney, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET BankBalance=@bankMoney WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@bankMoney", bankMoney);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static void SetPlayerProfile(string profilePage, int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "UPDATE UserExt SET ProfilePage=@profilePage WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@profilePage", profilePage);
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
sqlCommand.ExecuteNonQuery();
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static string GetPlayerProfile(int id)
{
if (CheckUserExist(id))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT ProfilePage FROM UserExt WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", id);
sqlCommand.Prepare();
string profilePage = sqlCommand.ExecuteScalar().ToString();
return profilePage;
}
else
{
throw new KeyNotFoundException("Id " + id + " not found in database.");
}
}
public static string GetUsername(int userId)
{
if(CheckUserExist(userId))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT Username FROM Users WHERE Id=@id";
sqlCommand.Parameters.AddWithValue("@id", userId);
sqlCommand.Prepare();
string username = sqlCommand.ExecuteScalar().ToString();
return username;
}
else
{
throw new KeyNotFoundException("Id " + userId + " not found in database.");
}
}
public static byte[] GetPasswordHash(string username)
{
if(CheckUserExist(username))
{
MySqlCommand sqlCommand = db.CreateCommand();
sqlCommand.CommandText = "SELECT PassHash FROM Users WHERE Username=@name";
sqlCommand.Parameters.AddWithValue("@name", username);
sqlCommand.Prepare();
string expectedHash = sqlCommand.ExecuteScalar().ToString();
return Converters.StringToByteArray(expectedHash);
}
else
{
throw new KeyNotFoundException("Username " + username + " not found in database.");
}
}
}
}

View file

@ -1,60 +1,56 @@
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace Horse_Isle_Server
{
class Gamedata
{
public static string TileFlags;
public static int NewUserStartX;
public static int NewUserStartY;
// Messages
public static string NewUserMessage;
public static string AreaMessage;
public static string NothingMessage;
public static string LoginMessage;
public static void ReadGamedata()
{
if(!File.Exists(ConfigReader.GameDataFile))
{
Logger.ErrorPrint("Game Data JSON File: " + ConfigReader.GameDataFile + " Does not exist!");
return;
}
string jsonData = File.ReadAllText(ConfigReader.GameDataFile);
dynamic gameData = JsonConvert.DeserializeObject(jsonData);
int totalIsles = gameData.isles.Count;
for(int i = 0; i < totalIsles; i++)
{
World.Isle isle = new World.Isle();
isle.StartX = gameData.isles[i].start_x;
isle.StartY = gameData.isles[i].start_y;
isle.EndX = gameData.isles[i].end_x;
isle.EndY = gameData.isles[i].end_y;
isle.Tileset = gameData.isles[i].tileset;
isle.Name = gameData.isles[i].name;
Logger.DebugPrint("Registered Isle: " + isle.Name + " X " + isle.StartX + "-" + isle.EndX + " Y " + isle.StartY + "-" + isle.EndY + " tileset: " + isle.Tileset);
World.Isles.Add(isle);
}
NewUserMessage = gameData.new_user.starting_message;
NewUserStartX = gameData.new_user.starting_x;
NewUserStartY = gameData.new_user.starting_y;
LoginMessage = gameData.messages.login_format;
AreaMessage = gameData.messages.area_format;
NothingMessage = gameData.messages.nothing_message;
TileFlags = gameData.map_flags;
}
}
}
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Horse_Isle_Server
{
class Gamedata
{
public static void ReadGamedata()
{
if(!File.Exists(ConfigReader.GameDataFile))
{
Logger.ErrorPrint("Game Data JSON File: " + ConfigReader.GameDataFile + " Does not exist!");
return;
}
string jsonData = File.ReadAllText(ConfigReader.GameDataFile);
dynamic gameData = JsonConvert.DeserializeObject(jsonData);
int totalIsles = gameData.isles.Count;
for(int i = 0; i < totalIsles; i++)
{
World.Isle isle = new World.Isle();
isle.StartX = gameData.isles[i].start_x;
isle.StartY = gameData.isles[i].start_y;
isle.EndX = gameData.isles[i].end_x;
isle.EndY = gameData.isles[i].end_y;
isle.Tileset = gameData.isles[i].tileset;
isle.Name = gameData.isles[i].name;
Logger.DebugPrint("Registered Isle: " + isle.Name + " X " + isle.StartX + "-" + isle.EndX + " Y " + isle.StartY + "-" + isle.EndY + " tileset: " + isle.Tileset);
World.Isles.Add(isle);
}
Messages.NewUserMessage = gameData.new_user.starting_message;
Map.NewUserStartX = gameData.new_user.starting_x;
Map.NewUserStartY = gameData.new_user.starting_y;
Messages.LoginFormat = gameData.messages.login_format;
Messages.AreaMessage = gameData.messages.area_format;
Messages.NothingMessage = gameData.messages.nothing_message;
Messages.MotdFormat = gameData.messages.motd_format;
JArray overlayTileDepth = gameData.tile_paramaters.overlay_tiles.tile_depth;
JArray terrainTilePassibility = gameData.tile_paramaters.terrain_tiles.passibility;
Map.OverlayTileDepth = overlayTileDepth.ToObject<int[]>();
Map.TerrainTilePassibility = terrainTilePassibility.ToObject<bool[]>();
}
}
}

View file

@ -1,110 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C48CBD82-AB30-494A-8FFA-4DE7069B5827}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Horse_Isle_Server</RootNamespace>
<AssemblyName>Horse Isle Server</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="MySqlConnector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92, processorArchitecture=MSIL">
<HintPath>..\packages\MySqlConnector.1.0.1\lib\net471\MySqlConnector.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.0\lib\netstandard2.0\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.3.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Authentication.cs" />
<Compile Include="Client.cs" />
<Compile Include="Converters.cs" />
<Compile Include="Database.cs" />
<Compile Include="Gamedata.cs" />
<Compile Include="Logger.cs" />
<Compile Include="ConfigReader.cs" />
<Compile Include="CrossDomainPolicy.cs" />
<Compile Include="Mailbox.cs" />
<Compile Include="Map.cs" />
<Compile Include="Messages.cs" />
<Compile Include="PacketBuilder.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Server.cs" />
<Compile Include="User.cs" />
<Compile Include="World.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="Resources\server.properties" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Resources\default_cross_domain.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C48CBD82-AB30-494A-8FFA-4DE7069B5827}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Horse_Isle_Server</RootNamespace>
<AssemblyName>Horse Isle Server</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="MySqlConnector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92, processorArchitecture=MSIL">
<HintPath>..\packages\MySqlConnector.1.0.1\lib\net471\MySqlConnector.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.0\lib\netstandard2.0\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.3.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Authentication.cs" />
<Compile Include="Client.cs" />
<Compile Include="Converters.cs" />
<Compile Include="Database.cs" />
<Compile Include="Gamedata.cs" />
<Compile Include="Logger.cs" />
<Compile Include="ConfigReader.cs" />
<Compile Include="CrossDomainPolicy.cs" />
<Compile Include="Mailbox.cs" />
<Compile Include="Map.cs" />
<Compile Include="Messages.cs" />
<Compile Include="PacketBuilder.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Server.cs" />
<Compile Include="User.cs" />
<Compile Include="World.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="Resources\server.properties" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Resources\default_cross_domain.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -1,25 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Logger
{
public static void DebugPrint(string text)
{
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] " + text);
}
public static void WarnPrint(string text)
{
Console.WriteLine("[WARN] " + text);
}
public static void ErrorPrint(string text)
{
Console.WriteLine("[ERROR] " + text);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Logger
{
public static void DebugPrint(string text)
{
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] " + text);
}
public static void WarnPrint(string text)
{
Console.WriteLine("[WARN] " + text);
}
public static void ErrorPrint(string text)
{
Console.WriteLine("[ERROR] " + text);
}
}
}

View file

@ -1,20 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Mailbox
{
private User baseUser;
public int MailCount;
public Mailbox(User user)
{
MailCount = Database.CheckMailcount(user.Id);
baseUser = user;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Mailbox
{
private User baseUser;
public int MailCount;
public Mailbox(User user)
{
MailCount = Database.CheckMailcount(user.Id);
baseUser = user;
}
}
}

View file

@ -1,42 +1,51 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Map
{
public static Bitmap MapData;
public static Bitmap oMapData;
public static int GetTileId(int x, int y, bool overlay)
{
if ((x > MapData.Width || x < 0) || (y > MapData.Height || y < 0)) // Outside map?
return 0x01;
if (overlay)
return oMapData.GetPixel(x, y).B;
else
return MapData.GetPixel(x, y).B;
}
public static bool CheckPassable(int x, int y)
{
return true; // not implemented yet
}
public static void OpenMap()
{
if(!File.Exists(ConfigReader.MapFile) || !File.Exists(ConfigReader.OverlayMapFile))
{
Logger.ErrorPrint("Map file not found.");
return;
}
MapData = new Bitmap(ConfigReader.MapFile);
oMapData = new Bitmap(ConfigReader.OverlayMapFile);
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Map
{
public static int[] OverlayTileDepth;
public static bool[] TerrainTilePassibility;
public static Bitmap MapData;
public static int NewUserStartX;
public static int NewUserStartY;
public static int GetTileId(int x, int y, bool overlay)
{
if ((x > MapData.Width || x < 0) || (y > MapData.Height || y < 0)) // Outside map?
return 0x1;
if (overlay)
return MapData.GetPixel(x, y).R;
else
return MapData.GetPixel(x, y).B;
}
public static bool CheckPassable(int x, int y)
{
int tileId = GetTileId(x, y, false);
bool passable = TerrainTilePassibility[tileId-1];
Logger.DebugPrint("Checking tile passibility for tileid: " + tileId + " at " + x + "," + y+" passable: " +passable);
return passable;
}
public static void OpenMap()
{
if(!File.Exists(ConfigReader.MapFile))
{
Logger.ErrorPrint("Map file not found.");
return;
}
MapData = new Bitmap(ConfigReader.MapFile);
}
}
}

View file

@ -1,34 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Messages
{
public static string LoginMessage(string username)
{
return Gamedata.LoginMessage.Replace("%USERNAME%", username);
}
public static string LocationData(int x, int y)
{
string message = "";
try
{
World.Isle isle = World.GetIsle(x, y);
message = Gamedata.AreaMessage.Replace("%AREA%", isle.Name);
}
catch (Exception) { }
int[] itemIds = World.GetDroppedItems(x, y);
if (itemIds.Length == 0)
message += Gamedata.NothingMessage;
return message;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Messages
{
public static string NewUserMessage;
public static string AreaMessage;
public static string NothingMessage;
public static string LoginFormat;
public static string MotdFormat;
public static string GetMOTD()
{
return MotdFormat.Replace("%MOTD%", ConfigReader.Motd);
}
public static string GetLoginMessage(string username)
{
return LoginFormat.Replace("%USERNAME%", username);
}
public static string LocationData(int x, int y)
{
string message = "";
try
{
World.Isle isle = World.GetIsle(x, y);
message = AreaMessage.Replace("%AREA%", isle.Name);
}
catch (Exception) { }
int[] itemIds = World.GetDroppedItems(x, y);
if (itemIds.Length == 0)
message += NothingMessage;
return message;
}
}
}

View file

@ -1,412 +1,442 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class PacketBuilder
{
public const byte PACKET_TERMINATOR = 0x00;
public const byte PACKET_A_TERMINATOR = 0x0A;
public const byte PACKET_LOGIN = 0x7F;
public const byte PACKET_CHAT = 0x14;
public const byte PACKET_MOVE = 0x15;
public const byte PACKET_USERINFO = 0x81;
public const byte PACKET_WORLD = 0x7A;
public const byte PACKET_BASE_STATS = 0x7B;
public const byte PACKET_PLACE_INFO = 0x1E;
public const byte PACKET_AREA_DEFS = 0x79;
public const byte PACKET_TILE_FLAGS = 0x75;
public const byte AREA_SEPERATOR = 0x5E;
public const byte MOVE_UP = 0x14;
public const byte MOVE_DOWN = 0x15;
public const byte MOVE_RIGHT = 0x16;
public const byte MOVE_LEFT = 0x17;
public const byte MOVE_EXIT = 0x10;
public const byte CHAT_BOTTOM_LEFT = 0x14;
public const byte CHAT_BOTTOM_RIGHT = 0x15;
public const byte LOGIN_INVALID_USER_PASS = 0x15;
public const byte LOGIN_SUCCESS = 0x14;
public const byte DIRECTION_UP = 0;
public const byte DIRECTION_RIGHT = 1;
public const byte DIRECTION_DOWN = 2;
public const byte DIRECTION_LEFT = 3;
public const byte DIRECTION_LOGIN = 4;
public static byte[] CreateLoginPacket(bool Success)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_LOGIN);
if (Success)
ms.WriteByte(LOGIN_SUCCESS);
else
ms.WriteByte(LOGIN_INVALID_USER_PASS);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateMovementPacket(int x, int y,int charId,int facing, int direction, bool walk)
{
// Header information
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_MOVE);
ms.WriteByte((byte)((x / 64) + 20)); //1
ms.WriteByte((byte)((x % 64) + 20)); //2
ms.WriteByte((byte)((y / 64) + 20)); //3
ms.WriteByte((byte)((y % 64) + 20)); //4
ms.WriteByte((byte)(facing + 20)); //5
ms.WriteByte((byte)((charId / 64) + 20)); //6
ms.WriteByte((byte)((charId % 64) + 20)); //7
ms.WriteByte((byte)(direction + 20)); //8
ms.WriteByte((byte)(Convert.ToInt32(walk) + 20)); //9
// Map Data
if (direction >= 20)
{
direction -= 20;
}
int ystart = y - 3;
int xstart = x - 2;
if (direction == DIRECTION_UP)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart, false);
int otileId = Map.GetTileId(xstart + relx, ystart, true);
if (tileId == 290)
tileId -= 100;
if (otileId == 290)
otileId -= 100;
ms.WriteByte((byte)tileId);
ms.WriteByte((byte)otileId);
}
}
if (direction == DIRECTION_LEFT)
{
for (int rely = 0; rely <= 9; rely++)
{
int tileId = Map.GetTileId(xstart, ystart + rely, false);
int otileId = Map.GetTileId(xstart, ystart + rely, true);
if (tileId == 290)
tileId -= 100;
if (otileId == 290)
otileId -= 100;
ms.WriteByte((byte)tileId);
ms.WriteByte((byte)otileId);
}
}
if (direction == DIRECTION_RIGHT)
{
for (int rely = 0; rely <= 9; rely++)
{
int tileId = Map.GetTileId(xstart + 12, ystart + rely, false);
int otileId = Map.GetTileId(xstart + 12, ystart + rely, true);
if (tileId == 290)
tileId -= 100;
if (otileId == 290)
otileId -= 100;
ms.WriteByte((byte)tileId);
ms.WriteByte((byte)otileId);
}
}
if (direction == DIRECTION_DOWN)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart + 9, false);
int otileId = Map.GetTileId(xstart + relx, ystart + 9, true);
if (tileId == 290)
tileId -= 100;
if (otileId == 290)
otileId -= 100;
ms.WriteByte((byte)tileId);
ms.WriteByte((byte)otileId);
}
}
if (direction == DIRECTION_LOGIN)
{
for(int rely = 0; rely <= 9; rely++)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart + rely, false);
int otileId = Map.GetTileId(xstart + relx, ystart + rely, true);
if (tileId == 290)
tileId -= 100;
if(otileId == 290)
otileId -= 100;
ms.WriteByte((byte)tileId);
ms.WriteByte((byte)otileId);
}
}
}
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreatePlaceInfo(string formattedText)
{
byte[] strBytes = Encoding.UTF8.GetBytes(formattedText);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_PLACE_INFO);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateChat(string formattedText, byte chatWindow)
{
byte[] strBytes = Encoding.UTF8.GetBytes(formattedText);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_CHAT);
ms.WriteByte(chatWindow);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateAreaMessage(int x, int y)
{
string locationStr = Messages.LocationData(x, y);
return CreatePlaceInfo(locationStr);
}
public static byte[] CreateLoginMessage(string username)
{
string formattedStr = Messages.LoginMessage(username);
return CreateChat(formattedStr,CHAT_BOTTOM_RIGHT);
}
public static byte[] CreateWorldData(int gameTime, int gameDay, int gameYear, string weather)
{
byte[] strBytes = Encoding.UTF8.GetBytes(weather);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_WORLD);
ms.WriteByte((byte)((gameTime / 64) + 20));
ms.WriteByte((byte)((gameTime % 64) + 20));
ms.WriteByte((byte)((gameDay / 64) + 20));
ms.WriteByte((byte)((gameDay % 64) + 20));
ms.WriteByte((byte)((gameYear / 64) + 20));
ms.WriteByte((byte)((gameYear % 64) + 20));
ms.Write(strBytes,0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateIsleData(World.Isle[] isles)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_AREA_DEFS);
foreach(World.Isle isle in isles)
{
byte[] strBytes = Encoding.UTF8.GetBytes(isle.Name);
ms.WriteByte(AREA_SEPERATOR);
ms.WriteByte((byte)((isle.StartX / 64) + 20));
ms.WriteByte((byte)((isle.StartX % 64) + 20));
ms.WriteByte((byte)((isle.EndX / 64) + 20));
ms.WriteByte((byte)((isle.EndX % 64) + 20));
ms.WriteByte((byte)((isle.StartY / 64) + 20));
ms.WriteByte((byte)((isle.StartY % 64) + 20));
ms.WriteByte((byte)((isle.EndY / 64) + 20));
ms.WriteByte((byte)((isle.EndY % 64) + 20));
ms.WriteByte((byte)isle.Tileset.ToString()[0]);
ms.Write(strBytes, 0x00, strBytes.Length);
}
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateBaseStats(int money, int playerCount, int mail)
{
byte[] moneyStrBytes = Encoding.UTF8.GetBytes(money.ToString());
byte[] playerStrBytes = Encoding.UTF8.GetBytes(playerCount.ToString());
byte[] mailStrBytes = Encoding.UTF8.GetBytes(mail.ToString());
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_BASE_STATS);
ms.Write(moneyStrBytes, 0x00, moneyStrBytes.Length);
ms.WriteByte((byte)'|');
ms.Write(playerStrBytes, 0x00, playerStrBytes.Length);
ms.WriteByte((byte)'|');
ms.Write(mailStrBytes, 0x00, mailStrBytes.Length);
ms.WriteByte((byte)'|');
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateTileFlags(string tileFlags)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_TILE_FLAGS);
byte[] strBytes = Encoding.UTF8.GetBytes(tileFlags);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateSecCode(byte[] SecCodeSeed, int SecCodeInc, bool Admin, bool Moderator)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_USERINFO);
ms.WriteByte((byte)(SecCodeSeed[0] + 33));
ms.WriteByte((byte)(SecCodeSeed[1] + 33));
ms.WriteByte((byte)(SecCodeSeed[2] + 33));
ms.WriteByte((byte)(SecCodeInc + 33));
char userType = 'N'; // Normal?
if (Moderator)
userType = 'M';
if (Admin)
userType = 'A';
ms.WriteByte((byte)userType);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateUserInfo(Client client)
{
MemoryStream ms = new MemoryStream();
if(!client.LoggedIn)
throw new Exception("Client is not logged in.");
User user = client.LoggedinUser;
byte[] MovementPacket = CreateMovementPacket(user.X, user.Y, user.CharacterId, DIRECTION_DOWN, DIRECTION_LOGIN, false);
ms.Write(MovementPacket, 0x00, MovementPacket.Length);
byte[] LoginMessage = CreateLoginMessage(user.Username);
ms.Write(LoginMessage, 0x00, LoginMessage.Length);
World.Time time = World.GetGameTime();
int timestamp = time.hours * 60;
timestamp += time.minutes;
byte[] WorldData = CreateWorldData(timestamp, time.days, time.year, World.GetWeather());
ms.Write(WorldData, 0x00, WorldData.Length);
byte[] SecCodePacket = CreateSecCode(user.SecCodeSeeds, user.SecCodeInc, user.Administrator, user.Moderator);
ms.Write(SecCodePacket, 0x00, SecCodePacket.Length);
byte[] BaseStatsPacketData = CreateBaseStats(user.Money, Server.GetNumberOfPlayers(), user.MailBox.MailCount);
ms.Write(BaseStatsPacketData, 0x00, BaseStatsPacketData.Length);
byte[] AreaMessage = CreateAreaMessage(user.X,user.Y);
ms.Write(AreaMessage, 0x00, AreaMessage.Length);
byte[] IsleData = CreateIsleData(World.Isles.ToArray());
ms.Write(IsleData, 0x00, IsleData.Length);
byte[] TileFlags = CreateTileFlags(Gamedata.TileFlags);
ms.Write(TileFlags, 0x00, TileFlags.Length);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class PacketBuilder
{
public const byte PACKET_TERMINATOR = 0x00;
public const byte PACKET_A_TERMINATOR = 0x0A;
public const byte PACKET_LOGIN = 0x7F;
public const byte PACKET_CHAT = 0x14;
public const byte PACKET_MOVE = 0x15;
public const byte PACKET_USERINFO = 0x81;
public const byte PACKET_WORLD = 0x7A;
public const byte PACKET_BASE_STATS = 0x7B;
public const byte PACKET_PLACE_INFO = 0x1E;
public const byte PACKET_AREA_DEFS = 0x79;
public const byte PACKET_ANNOUNCEMENT = 0x7E;
public const byte PACKET_TILE_FLAGS = 0x75;
public const byte AREA_SEPERATOR = 0x5E;
public const byte MOVE_UP = 0x14;
public const byte MOVE_DOWN = 0x15;
public const byte MOVE_RIGHT = 0x16;
public const byte MOVE_LEFT = 0x17;
public const byte MOVE_EXIT = 0x10;
public const byte CHAT_BOTTOM_LEFT = 0x14;
public const byte CHAT_BOTTOM_RIGHT = 0x15;
public const byte LOGIN_INVALID_USER_PASS = 0x15;
public const byte LOGIN_SUCCESS = 0x14;
public const byte DIRECTION_UP = 0;
public const byte DIRECTION_RIGHT = 1;
public const byte DIRECTION_DOWN = 2;
public const byte DIRECTION_LEFT = 3;
public const byte DIRECTION_LOGIN = 4;
public const byte DIRECTION_NONE = 10;
public static byte[] CreateLoginPacket(bool Success)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_LOGIN);
if (Success)
ms.WriteByte(LOGIN_SUCCESS);
else
ms.WriteByte(LOGIN_INVALID_USER_PASS);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateMovementPacket(int x, int y,int charId,int facing, int direction, bool walk)
{
// Header information
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_MOVE);
ms.WriteByte((byte)(((x-4) / 64) + 20)); //1
ms.WriteByte((byte)(((x-4) % 64) + 20)); //2
ms.WriteByte((byte)(((y-1) / 64) + 20)); //3
ms.WriteByte((byte)(((y-1) % 64) + 20)); //4
ms.WriteByte((byte)(facing + 20)); //5
ms.WriteByte((byte)((charId / 64) + 20)); //6
ms.WriteByte((byte)((charId % 64) + 20)); //7
ms.WriteByte((byte)(direction + 20)); //8
ms.WriteByte((byte)(Convert.ToInt32(walk) + 20)); //9
// Map Data
if (direction >= 20)
{
direction -= 20;
}
int ystart = y - 4;
int xstart = x - 6;
if (direction == DIRECTION_UP)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart, false);
int otileId = Map.GetTileId(xstart + relx, ystart, true);
ms.WriteByte((byte)tileId);
if (tileId == 190)
ms.WriteByte((byte)0x5B);
ms.WriteByte((byte)otileId);
if (otileId == 190)
ms.WriteByte((byte)0x5A);
}
}
if (direction == DIRECTION_LEFT)
{
for (int rely = 0; rely <= 9; rely++)
{
int tileId = Map.GetTileId(xstart, ystart + rely, false);
int otileId = Map.GetTileId(xstart, ystart + rely, true);
ms.WriteByte((byte)tileId);
if (tileId == 190)
ms.WriteByte((byte)0x5B);
ms.WriteByte((byte)otileId);
if (otileId == 190)
ms.WriteByte((byte)0x5A);
}
}
if (direction == DIRECTION_RIGHT)
{
for (int rely = 0; rely <= 9; rely++)
{
int tileId = Map.GetTileId(xstart + 12, ystart + rely, false);
int otileId = Map.GetTileId(xstart + 12, ystart + rely, true);
ms.WriteByte((byte)tileId);
if (tileId == 190)
ms.WriteByte((byte)0x5B);
ms.WriteByte((byte)otileId);
if (otileId == 190)
ms.WriteByte((byte)0x5A);
}
}
if (direction == DIRECTION_DOWN)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart + 9, false);
int otileId = Map.GetTileId(xstart + relx, ystart + 9, true);
ms.WriteByte((byte)tileId);
if (tileId == 190)
ms.WriteByte((byte)0x5B);
ms.WriteByte((byte)otileId);
if (otileId == 190)
ms.WriteByte((byte)0x5A);
}
}
if (direction == DIRECTION_LOGIN)
{
for(int rely = 0; rely <= 9; rely++)
{
for (int relx = 0; relx <= 12; relx++)
{
int tileId = Map.GetTileId(xstart + relx, ystart + rely, false);
int otileId = Map.GetTileId(xstart + relx, ystart + rely, true);
ms.WriteByte((byte)tileId);
if (tileId == 190)
ms.WriteByte((byte)0x5B);
ms.WriteByte((byte)otileId);
if (otileId == 190)
ms.WriteByte((byte)0x5A);
}
}
}
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
Logger.DebugPrint(BitConverter.ToString(Packet).Replace('-', ' '));
return Packet;
}
public static byte[] CreatePlaceInfo(string formattedText)
{
byte[] strBytes = Encoding.UTF8.GetBytes(formattedText);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_PLACE_INFO);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateChat(string formattedText, byte chatWindow)
{
byte[] strBytes = Encoding.UTF8.GetBytes(formattedText);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_CHAT);
ms.WriteByte(chatWindow);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateWorldData(int gameTime, int gameDay, int gameYear, string weather)
{
byte[] strBytes = Encoding.UTF8.GetBytes(weather);
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_WORLD);
ms.WriteByte((byte)((gameTime / 64) + 20));
ms.WriteByte((byte)((gameTime % 64) + 20));
ms.WriteByte((byte)((gameDay / 64) + 20));
ms.WriteByte((byte)((gameDay % 64) + 20));
ms.WriteByte((byte)((gameYear / 64) + 20));
ms.WriteByte((byte)((gameYear % 64) + 20));
ms.Write(strBytes,0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateIsleData(World.Isle[] isles)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_AREA_DEFS);
foreach(World.Isle isle in isles)
{
byte[] strBytes = Encoding.UTF8.GetBytes(isle.Name);
ms.WriteByte(AREA_SEPERATOR);
ms.WriteByte((byte)(((isle.StartX - 4) / 64) + 20));
ms.WriteByte((byte)(((isle.StartX - 4) % 64) + 20));
ms.WriteByte((byte)(((isle.EndX - 4) / 64) + 20));
ms.WriteByte((byte)(((isle.EndX - 4) % 64) + 20));
ms.WriteByte((byte)(((isle.StartY - 1) / 64) + 20));
ms.WriteByte((byte)(((isle.StartY - 1) % 64) + 20));
ms.WriteByte((byte)(((isle.EndY - 1) / 64) + 20));
ms.WriteByte((byte)(((isle.EndY - 1) % 64) + 20));
ms.WriteByte((byte)isle.Tileset.ToString()[0]);
ms.Write(strBytes, 0x00, strBytes.Length);
}
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateBaseStats(int money, int playerCount, int mail)
{
byte[] moneyStrBytes = Encoding.UTF8.GetBytes(money.ToString());
byte[] playerStrBytes = Encoding.UTF8.GetBytes(playerCount.ToString());
byte[] mailStrBytes = Encoding.UTF8.GetBytes(mail.ToString());
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_BASE_STATS);
ms.Write(moneyStrBytes, 0x00, moneyStrBytes.Length);
ms.WriteByte((byte)'|');
ms.Write(playerStrBytes, 0x00, playerStrBytes.Length);
ms.WriteByte((byte)'|');
ms.Write(mailStrBytes, 0x00, mailStrBytes.Length);
ms.WriteByte((byte)'|');
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateTileOverlayFlags(int[] tileDepthFlags)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_TILE_FLAGS);
foreach(int tileDepthFlag in tileDepthFlags)
{
ms.WriteByte((byte)tileDepthFlag.ToString()[0]);
}
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateSecCode(byte[] SecCodeSeed, int SecCodeInc, bool Admin, bool Moderator)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_USERINFO);
ms.WriteByte((byte)(SecCodeSeed[0] + 33));
ms.WriteByte((byte)(SecCodeSeed[1] + 33));
ms.WriteByte((byte)(SecCodeSeed[2] + 33));
ms.WriteByte((byte)(SecCodeInc + 33));
char userType = 'N'; // Normal?
if (Moderator)
userType = 'M';
if (Admin)
userType = 'A';
ms.WriteByte((byte)userType);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateAnnouncement(string announcement)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte(PACKET_ANNOUNCEMENT);
byte[] strBytes = Encoding.UTF8.GetBytes(announcement);
ms.Write(strBytes, 0x00, strBytes.Length);
ms.WriteByte(PACKET_TERMINATOR);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
public static byte[] CreateAreaMessage(int x, int y)
{
string locationStr = Messages.LocationData(x, y);
return CreatePlaceInfo(locationStr);
}
public static byte[] CreateMotd()
{
string formattedMotd = Messages.GetMOTD();
return CreateAnnouncement(formattedMotd);
}
public static byte[] CreateLoginMessage(string username)
{
string formattedStr = Messages.GetLoginMessage(username);
return CreateChat(formattedStr, CHAT_BOTTOM_RIGHT);
}
public static byte[] CreateUserInfo(Client client)
{
MemoryStream ms = new MemoryStream();
if(!client.LoggedIn)
throw new Exception("Client is not logged in.");
User user = client.LoggedinUser;
byte[] MovementPacket = CreateMovementPacket(user.X, user.Y, user.CharacterId, DIRECTION_DOWN, DIRECTION_LOGIN, true);
ms.Write(MovementPacket, 0x00, MovementPacket.Length);
byte[] LoginMessage = CreateLoginMessage(user.Username);
ms.Write(LoginMessage, 0x00, LoginMessage.Length);
World.Time time = World.GetGameTime();
int timestamp = time.hours * 60;
timestamp += time.minutes;
byte[] WorldData = CreateWorldData(timestamp, time.days, time.year, World.GetWeather());
ms.Write(WorldData, 0x00, WorldData.Length);
byte[] SecCodePacket = CreateSecCode(user.SecCodeSeeds, user.SecCodeInc, user.Administrator, user.Moderator);
ms.Write(SecCodePacket, 0x00, SecCodePacket.Length);
byte[] BaseStatsPacketData = CreateBaseStats(user.Money, Server.GetNumberOfPlayers(), user.MailBox.MailCount);
ms.Write(BaseStatsPacketData, 0x00, BaseStatsPacketData.Length);
byte[] AreaMessage = CreateAreaMessage(user.X,user.Y);
ms.Write(AreaMessage, 0x00, AreaMessage.Length);
byte[] IsleData = CreateIsleData(World.Isles.ToArray());
ms.Write(IsleData, 0x00, IsleData.Length);
byte[] TileFlags = CreateTileOverlayFlags(Map.OverlayTileDepth);
ms.Write(TileFlags, 0x00, TileFlags.Length);
byte[] MotdData = CreateMotd();
ms.Write(MotdData, 0x00, MotdData.Length);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] Packet = ms.ToArray();
ms.Dispose();
return Packet;
}
}
}

View file

@ -1,21 +1,45 @@
using System;
using System.IO;
using System.Reflection;
namespace Horse_Isle_Server
{
class Program
{
static void Main(string[] args)
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
ConfigReader.OpenConfig();
CrossDomainPolicy.GetPolicy();
Database.OpenDatabase();
Map.OpenMap();
Gamedata.ReadGamedata();
Server.StartServer();
}
}
}
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
namespace Horse_Isle_Server
{
class Program
{
static void Main(string[] args)
{
/*
Bitmap mbmp = new Bitmap("MapData.bmp");
Bitmap bmp = new Bitmap("oMapData.bmp");
Console.WriteLine(bmp.PixelFormat);
Bitmap bbmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb);
for(int x = 0; x < bmp.Width; x++)
{
for(int y = 0; y < bmp.Height; y++)
{
Color col = mbmp.GetPixel(x, y);
Color col2 = bmp.GetPixel(x, y);
bbmp.SetPixel(x,y,Color.FromArgb(col2.B, 0, col.B));
}
}
bbmp.Save("MapData2.bmp", ImageFormat.Bmp);
Console.WriteLine("image checked");
*/
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
ConfigReader.OpenConfig();
CrossDomainPolicy.GetPolicy();
Database.OpenDatabase();
Map.OpenMap();
Gamedata.ReadGamedata();
Server.StartServer();
}
}
}

View file

@ -1,36 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Horse Isle Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Horse Isle Server")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c48cbd82-ab30-494a-8ffa-4de7069b5827")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Horse Isle Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Horse Isle Server")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c48cbd82-ab30-494a-8ffa-4de7069b5827")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -1,104 +1,104 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Horse_Isle_Server.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Horse_Isle_Server.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &lt;cross-domain-policy&gt;
/// &lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;1080&quot; secure=&quot;false&quot;/&gt;
///&lt;/cross-domain-policy&gt;.
/// </summary>
internal static string DefaultCrossDomain {
get {
return ResourceManager.GetString("DefaultCrossDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to # Horse Isle Server Default Configuration File
///
///# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
///ip=0.0.0.0
///# Port the server will bind to (default: 1080)
///port=1080
///
///# MariaDB Database
///db_ip=127.0.0.1
///db_username=root
///db_password=test123
///db_port=3306
///
///# Map Data
///map=MapData.bmp
///overlaymap=oMapData.bmp
///
///# Cross-Domain Policy File
///crossdomain=&quot;CrossDomainPolicy.xml
///
///# Should print debug logs
///debug=false.
/// </summary>
internal static string DefaultServerProperties {
get {
return ResourceManager.GetString("DefaultServerProperties", resourceCulture);
}
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Horse_Isle_Server.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Horse_Isle_Server.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &lt;cross-domain-policy&gt;
/// &lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;1080&quot; secure=&quot;false&quot;/&gt;
///&lt;/cross-domain-policy&gt;.
/// </summary>
internal static string DefaultCrossDomain {
get {
return ResourceManager.GetString("DefaultCrossDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to # Horse Isle Server Default Configuration File
///
///# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
///ip=0.0.0.0
///# Port the server will bind to (default: 1080)
///port=1080
///
///# MariaDB Database
///db_ip=127.0.0.1
///db_username=root
///db_password=test123
///db_port=3306
///
///# Map Data
///map=MapData.bmp
///overlaymap=oMapData.bmp
///
///# Cross-Domain Policy File
///crossdomain=&quot;CrossDomainPolicy.xml
///
///# Should print debug logs
///debug=false.
/// </summary>
internal static string DefaultServerProperties {
get {
return ResourceManager.GetString("DefaultServerProperties", resourceCulture);
}
}
}
}

View file

@ -1,127 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="DefaultCrossDomain" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\default_cross_domain.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<data name="DefaultServerProperties" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\server.properties;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="DefaultCrossDomain" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\default_cross_domain.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<data name="DefaultServerProperties" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\server.properties;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
</root>

View file

@ -1,3 +1,3 @@
<cross-domain-policy>
<allow-access-from domain="*" to-ports="12321" secure="false"/>
<cross-domain-policy>
<allow-access-from domain="*" to-ports="12321" secure="false"/>
</cross-domain-policy>

View file

@ -1,29 +1,28 @@
# Horse Isle Server Default Configuration File
# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
ip=0.0.0.0
# Port the server will bind to (default: 12321)
port=12321
# MariaDB Database
db_ip=127.0.0.1
db_name=beta
db_username=root
db_password=test123
db_port=3306
# Map Data
map=MapData.bmp
overlaymap=oMapData.bmp
# Game Data JSON
gamedata=gamedata.json
# Cross-Domain Policy File
crossdomain=CrossDomainPolicy.xml
# Red Text Stating "Todays Note:"
motd=April 11, 2020. New breed, Camarillo White Horse. Two new quests.
# Should print debug logs
# Horse Isle Server Default Configuration File
# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
ip=0.0.0.0
# Port the server will bind to (default: 12321)
port=12321
# MariaDB Database
db_ip=127.0.0.1
db_name=beta
db_username=root
db_password=test123
db_port=3306
# Map Data
map=MapDataCombined.bmp
# Game Data JSON
gamedata=gamedata.json
# Cross-Domain Policy File
crossdomain=CrossDomainPolicy.xml
# Red Text Stating "Todays Note:"
motd=April 11, 2020. New breed, Camarillo White Horse. Two new quests.
# Should print debug logs
debug=false

View file

@ -1,154 +1,186 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Server
{
public static Socket ServerSocket;
public static List<Client> ConnectedClients = new List<Client>();
public static void OnCrossdomainPolicyRequest(Client sender) // When a cross-domain-policy request is received.
{
Logger.DebugPrint("Cross-Domain-Policy request received from: " + sender.RemoteIp);
byte[] crossDomainPolicyResponse = CrossDomainPolicy.GetPolicy(); // Generate response packet
sender.SendPacket(crossDomainPolicyResponse); // Send to client.
}
public static void OnUserInfoRequest(Client sender, byte[] packet)
{
if (!sender.LoggedIn)
{
Logger.ErrorPrint(sender.RemoteIp + " Requested user information when not logged in.");
return;
}
Logger.DebugPrint(sender.LoggedinUser.Username + " Requesting user information.");
byte[] userInfoPackets = PacketBuilder.CreateUserInfo(sender);
sender.SendPacket(userInfoPackets);
}
public static void OnMovementPacket(Client sender, byte[] packet)
{
if (!sender.LoggedIn)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent movement packet when not logged in.");
return;
}
User loggedInUser = sender.LoggedinUser;
byte movementDirection = packet[1];
switch(movementDirection)
{
case PacketBuilder.MOVE_UP:
if(Map.CheckPassable(loggedInUser.X, loggedInUser.Y+1))
loggedInUser.Y -= 1;
byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_UP, true);
sender.SendPacket(moveUpResponse);
break;
case PacketBuilder.MOVE_LEFT:
if (Map.CheckPassable(loggedInUser.X - 1, loggedInUser.Y))
loggedInUser.X -= 1;
byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_LEFT, true);
sender.SendPacket(moveLeftResponse);
break;
case PacketBuilder.MOVE_RIGHT:
if (Map.CheckPassable(loggedInUser.X +1 , loggedInUser.Y))
loggedInUser.X += 1;
byte[] moveRightResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_RIGHT, true);
sender.SendPacket(moveRightResponse);
break;
case PacketBuilder.MOVE_DOWN:
if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y + 1))
loggedInUser.Y += 1;
byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_DOWN, true);
sender.SendPacket(moveDownResponse);
break;
}
byte[] tileData = PacketBuilder.CreateAreaMessage(loggedInUser.X, loggedInUser.Y);
sender.SendPacket(tileData);
}
public static void OnLoginRequest(Client sender, byte[] packet)
{
Logger.DebugPrint("Login request received from: " + sender.RemoteIp);
string loginRequestString = Encoding.UTF8.GetString(packet).Substring(1);
if (!loginRequestString.Contains('|') || packet.Length < 3)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent an invalid login request");
return;
}
if(packet[1] != PacketBuilder.PACKET_A_TERMINATOR)
{
string[] loginParts = loginRequestString.Split('|');
if (loginParts.Length < 3)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent a login request of invalid length. " + loginRequestString);
return;
}
int version = int.Parse(loginParts[0]);
string encryptedUsername = loginParts[1];
string encryptedPassword = loginParts[2];
string username = Authentication.DecryptLogin(encryptedUsername);
string password = Authentication.DecryptLogin(encryptedPassword);
if (Authentication.CheckPassword(username, password))
{
// Obtain user information
int userId = Database.GetUserid(username);
sender.Login(userId);
byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(true);
sender.SendPacket(ResponsePacket);
}
else
{
Logger.WarnPrint(sender.RemoteIp + " Attempted to login to: " + username + " with incorrect password " + password);
byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(false);
sender.SendPacket(ResponsePacket);
}
}
}
public static int GetNumberOfPlayers()
{
int count = 0;
foreach(Client client in ConnectedClients)
{
if (client.LoggedIn)
count++;
}
return count;
}
public static void StartServer()
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress hostIP = IPAddress.Parse(ConfigReader.BindIP);
IPEndPoint ep = new IPEndPoint(hostIP, ConfigReader.Port);
ServerSocket.Bind(ep);
Logger.DebugPrint("Binding to ip: " + ConfigReader.BindIP + " On port: " + ConfigReader.Port.ToString());
ServerSocket.Listen(10000);
while(true)
{
Logger.DebugPrint("Waiting for new connections...");
Socket cientSocket = ServerSocket.Accept();
Client client = new Client(cientSocket);
ConnectedClients.Add(client);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class Server
{
public static Socket ServerSocket;
public static List<Client> ConnectedClients = new List<Client>();
public static void OnCrossdomainPolicyRequest(Client sender) // When a cross-domain-policy request is received.
{
Logger.DebugPrint("Cross-Domain-Policy request received from: " + sender.RemoteIp);
byte[] crossDomainPolicyResponse = CrossDomainPolicy.GetPolicy(); // Generate response packet
sender.SendPacket(crossDomainPolicyResponse); // Send to client.
}
public static void OnUserInfoRequest(Client sender, byte[] packet)
{
if (!sender.LoggedIn)
{
Logger.ErrorPrint(sender.RemoteIp + " Requested user information when not logged in.");
return;
}
Logger.DebugPrint(sender.LoggedinUser.Username + " Requesting user information.");
byte[] userInfoPackets = PacketBuilder.CreateUserInfo(sender);
sender.SendPacket(userInfoPackets);
}
public static void OnMovementPacket(Client sender, byte[] packet)
{
if (!sender.LoggedIn)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent movement packet when not logged in.");
return;
}
User loggedInUser = sender.LoggedinUser;
byte movementDirection = packet[1];
if(movementDirection == PacketBuilder.MOVE_UP)
{
if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y - 1))
{
loggedInUser.Y -= 1;
byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_UP, true);
sender.SendPacket(moveUpResponse);
}
else
{
byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_NONE, false);
sender.SendPacket(moveUpResponse);
}
}
else if(movementDirection == PacketBuilder.MOVE_LEFT)
{
if (Map.CheckPassable(loggedInUser.X - 1, loggedInUser.Y))
{
loggedInUser.X -= 1;
byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_LEFT, true);
sender.SendPacket(moveLeftResponse);
}
else
{
byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_NONE, false);
sender.SendPacket(moveLeftResponse);
}
}
else if(movementDirection == PacketBuilder.MOVE_RIGHT)
{
if (Map.CheckPassable(loggedInUser.X + 1, loggedInUser.Y))
{
loggedInUser.X += 1;
byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_RIGHT, true);
sender.SendPacket(moveLeftResponse);
}
else
{
byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_NONE, false);
sender.SendPacket(moveLeftResponse);
}
}
else if(movementDirection == PacketBuilder.MOVE_DOWN)
{
if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y + 1))
{
loggedInUser.Y += 1;
byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_DOWN, true);
sender.SendPacket(moveDownResponse);
}
else
{
byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_NONE, false);
sender.SendPacket(moveDownResponse);
}
}
byte[] tileData = PacketBuilder.CreateAreaMessage(loggedInUser.X, loggedInUser.Y);
sender.SendPacket(tileData);
}
public static void OnLoginRequest(Client sender, byte[] packet)
{
Logger.DebugPrint("Login request received from: " + sender.RemoteIp);
string loginRequestString = Encoding.UTF8.GetString(packet).Substring(1);
if (!loginRequestString.Contains('|') || packet.Length < 3)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent an invalid login request");
return;
}
if(packet[1] != PacketBuilder.PACKET_A_TERMINATOR)
{
string[] loginParts = loginRequestString.Split('|');
if (loginParts.Length < 3)
{
Logger.ErrorPrint(sender.RemoteIp + " Sent a login request of invalid length. " + loginRequestString);
return;
}
int version = int.Parse(loginParts[0]);
string encryptedUsername = loginParts[1];
string encryptedPassword = loginParts[2];
string username = Authentication.DecryptLogin(encryptedUsername);
string password = Authentication.DecryptLogin(encryptedPassword);
if (Authentication.CheckPassword(username, password))
{
// Obtain user information
int userId = Database.GetUserid(username);
sender.Login(userId);
byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(true);
sender.SendPacket(ResponsePacket);
}
else
{
Logger.WarnPrint(sender.RemoteIp + " Attempted to login to: " + username + " with incorrect password " + password);
byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(false);
sender.SendPacket(ResponsePacket);
}
}
}
public static int GetNumberOfPlayers()
{
int count = 0;
foreach(Client client in ConnectedClients)
{
if (client.LoggedIn)
count++;
}
return count;
}
public static void StartServer()
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress hostIP = IPAddress.Parse(ConfigReader.BindIP);
IPEndPoint ep = new IPEndPoint(hostIP, ConfigReader.Port);
ServerSocket.Bind(ep);
Logger.DebugPrint("Binding to ip: " + ConfigReader.BindIP + " On port: " + ConfigReader.Port.ToString());
ServerSocket.Listen(10000);
while(true)
{
Logger.DebugPrint("Waiting for new connections...");
Socket cientSocket = ServerSocket.Accept();
Client client = new Client(cientSocket);
ConnectedClients.Add(client);
}
}
}
}

View file

@ -1,163 +1,163 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class User
{
public int Id;
public string Username;
public bool Administrator;
public bool Moderator;
public bool NewPlayer = false;
public Mailbox MailBox;
public string ProfilePage {
get
{
return profilePage;
}
set
{
Database.SetPlayerProfile(value, Id);
profilePage = value;
}
}
public int Money
{
get
{
return money;
}
set
{
Database.SetPlayerBankMoney(value, Id);
money = value;
}
}
public int BankMoney
{
get
{
return bankMoney;
}
set
{
Database.SetPlayerBankMoney(value, Id);
bankMoney = value;
}
}
public int X
{
get
{
return x;
}
set
{
Database.SetPlayerX(value, Id);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetPlayerY(value, Id);
y = value;
}
}
public int CharacterId
{
get
{
return charId;
}
set
{
Database.SetPlayerCharId(value, Id);
charId = value;
}
}
private int charId;
private string profilePage;
private int x;
private int y;
private int money;
private int bankMoney;
public byte[] SecCodeSeeds = new byte[3];
public int SecCodeInc = 0;
public int SecCodeCount = 0;
public byte[] GenerateSecCode()
{
var i = 0;
SecCodeCount++;
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] + SecCodeInc);
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] % 92);
i = SecCodeSeeds[0] + SecCodeSeeds[1] * SecCodeSeeds[2] - SecCodeSeeds[1];
i = Math.Abs(i);
i = i % 92;
byte[] SecCode = new byte[4];
SecCode[0] = (byte)(SecCodeSeeds[0] + 33);
SecCode[1] = (byte)(SecCodeSeeds[1] + 33);
SecCode[2] = (byte)(SecCodeSeeds[2] + 33);
SecCode[3] = (byte)(i + 33);
return SecCode;
}
public User(int UserId)
{
if (!Database.CheckUserExist(UserId))
throw new KeyNotFoundException("User " + UserId + " not found in database!");
if (!Database.CheckUserExtExists(UserId))
{
Database.CreateUserExt(UserId);
NewPlayer = true;
}
Id = UserId;
Username = Database.GetUsername(UserId);
Administrator = Database.CheckUserIsAdmin(Username);
Moderator = Database.CheckUserIsModerator(Username);
x = Database.GetPlayerX(UserId);
y = Database.GetPlayerY(UserId);
charId = Database.GetPlayerCharId(UserId);
money = Database.GetPlayerMoney(UserId);
bankMoney = Database.GetPlayerBankMoney(UserId);
profilePage = Database.GetPlayerProfile(UserId);
MailBox = new Mailbox(this);
// Generate SecCodes
Random rng = new Random();
SecCodeSeeds[0] = (byte)rng.Next(0, 255 - 33);
SecCodeSeeds[1] = (byte)rng.Next(0, 255 - 33);
SecCodeSeeds[2] = (byte)rng.Next(0, 255 - 33);
SecCodeInc = (byte)rng.Next(0, 255 - 33);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class User
{
public int Id;
public string Username;
public bool Administrator;
public bool Moderator;
public bool NewPlayer = false;
public Mailbox MailBox;
public string ProfilePage {
get
{
return profilePage;
}
set
{
Database.SetPlayerProfile(value, Id);
profilePage = value;
}
}
public int Money
{
get
{
return money;
}
set
{
Database.SetPlayerBankMoney(value, Id);
money = value;
}
}
public int BankMoney
{
get
{
return bankMoney;
}
set
{
Database.SetPlayerBankMoney(value, Id);
bankMoney = value;
}
}
public int X
{
get
{
return x;
}
set
{
Database.SetPlayerX(value, Id);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetPlayerY(value, Id);
y = value;
}
}
public int CharacterId
{
get
{
return charId;
}
set
{
Database.SetPlayerCharId(value, Id);
charId = value;
}
}
private int charId;
private string profilePage;
private int x;
private int y;
private int money;
private int bankMoney;
public byte[] SecCodeSeeds = new byte[3];
public int SecCodeInc = 0;
public int SecCodeCount = 0;
public byte[] GenerateSecCode()
{
var i = 0;
SecCodeCount++;
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] + SecCodeInc);
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] % 92);
i = SecCodeSeeds[0] + SecCodeSeeds[1] * SecCodeSeeds[2] - SecCodeSeeds[1];
i = Math.Abs(i);
i = i % 92;
byte[] SecCode = new byte[4];
SecCode[0] = (byte)(SecCodeSeeds[0] + 33);
SecCode[1] = (byte)(SecCodeSeeds[1] + 33);
SecCode[2] = (byte)(SecCodeSeeds[2] + 33);
SecCode[3] = (byte)(i + 33);
return SecCode;
}
public User(int UserId)
{
if (!Database.CheckUserExist(UserId))
throw new KeyNotFoundException("User " + UserId + " not found in database!");
if (!Database.CheckUserExtExists(UserId))
{
Database.CreateUserExt(UserId);
NewPlayer = true;
}
Id = UserId;
Username = Database.GetUsername(UserId);
Administrator = Database.CheckUserIsAdmin(Username);
Moderator = Database.CheckUserIsModerator(Username);
x = Database.GetPlayerX(UserId);
y = Database.GetPlayerY(UserId);
charId = Database.GetPlayerCharId(UserId);
money = Database.GetPlayerMoney(UserId);
bankMoney = Database.GetPlayerBankMoney(UserId);
profilePage = Database.GetPlayerProfile(UserId);
MailBox = new Mailbox(this);
// Generate SecCodes
Random rng = new Random();
SecCodeSeeds[0] = (byte)rng.Next(0, 255 - 33);
SecCodeSeeds[1] = (byte)rng.Next(0, 255 - 33);
SecCodeSeeds[2] = (byte)rng.Next(0, 255 - 33);
SecCodeInc = (byte)rng.Next(0, 255 - 33);
}
}
}

View file

@ -1,79 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class World
{
public struct Isle
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public int Tileset;
public string Name;
}
public struct Time
{
public int minutes;
public int hours;
public int days;
public int year;
}
public const int MINUTE = 4320;
public static List<Isle> Isles = new List<Isle>();
public static Time GetGameTime()
{
int epoch = Database.GetServerCreationTime();
DateTime serverCreationTime = DateTimeOffset.FromUnixTimeSeconds(epoch).DateTime;
DateTime currentTime = DateTime.Now;
TimeSpan difference = (currentTime.Date - currentTime.Date);
int totalMilis = Convert.ToInt32(difference.TotalMilliseconds);
int gameMinutes = totalMilis / MINUTE;
int gameHours = (totalMilis / MINUTE * 600);
int gameDays = (totalMilis / (MINUTE * 60) * 24);
int gameYears = ((totalMilis / (MINUTE * 60) * 24)*365);
Time time = new Time();
time.days = gameDays;
time.year = gameYears;
time.minutes = gameMinutes;
time.hours = gameHours;
return time;
}
public static Isle GetIsle(int x, int y)
{
foreach(Isle isle in Isles)
{
if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y)
{
return isle;
}
}
throw new KeyNotFoundException("x,y not in an isle!");
}
public static int[] GetDroppedItems(int x, int y)
{
return new int[] { }; // Not implemented yet.
}
public static string GetWeather()
{
return Database.GetWorldWeather();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Horse_Isle_Server
{
class World
{
public struct Isle
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public int Tileset;
public string Name;
}
public struct Time
{
public int minutes;
public int hours;
public int days;
public int year;
}
public const int MINUTE = 4320;
public static List<Isle> Isles = new List<Isle>();
public static Time GetGameTime()
{
int epoch = Database.GetServerCreationTime();
DateTime serverCreationTime = DateTimeOffset.FromUnixTimeSeconds(epoch).DateTime;
DateTime currentTime = DateTime.Now;
TimeSpan difference = (currentTime.Date - currentTime.Date);
int totalMilis = Convert.ToInt32(difference.TotalMilliseconds);
int gameMinutes = totalMilis / MINUTE;
int gameHours = (totalMilis / MINUTE * 600);
int gameDays = (totalMilis / (MINUTE * 60) * 24);
int gameYears = ((totalMilis / (MINUTE * 60) * 24)*365);
Time time = new Time();
time.days = gameDays;
time.year = gameYears;
time.minutes = gameMinutes;
time.hours = gameHours;
return time;
}
public static Isle GetIsle(int x, int y)
{
foreach(Isle isle in Isles)
{
if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y)
{
return isle;
}
}
throw new KeyNotFoundException("x,y not in an isle!");
}
public static int[] GetDroppedItems(int x, int y)
{
return new int[] { }; // Not implemented yet.
}
public static string GetWeather()
{
return Database.GetWorldWeather();
}
}
}

View file

@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MySqlConnector" version="1.0.1" targetFramework="net48" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net48" />
<package id="System.Buffers" version="4.4.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.0" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.3.0" targetFramework="net48" />
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MySqlConnector" version="1.0.1" targetFramework="net48" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net48" />
<package id="System.Buffers" version="4.4.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.0" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.3.0" targetFramework="net48" />
</packages>