Created by: Andrew
This commit is contained in:
Andrew
2016-08-27 22:43:23 -04:00
commit 6d74d5b59e
31 changed files with 3002 additions and 0 deletions

View File

@@ -0,0 +1,151 @@
using System;
using System.IO;
namespace KartExtreme.IO.Packet
{
public class InPacket : PacketBase
{
private readonly byte[] _buffer;
private int _index;
public override int Position
{
get { return _index; }
}
public override int Length
{
get { return _buffer.Length; }
}
public int Available
{
get
{
return _buffer.Length - _index;
}
}
public InPacket(byte[] packet)
{
_buffer = packet;
_index = 0;
}
private void CheckLength(int length)
{
if (_index + length > _buffer.Length || length < 0)
throw new PacketReadException("Not enough space");
}
public bool ReadBool()
{
return ReadByte() == 1;
}
public byte ReadByte()
{
CheckLength(1);
return _buffer[_index++];
}
public sbyte ReadSByte()
{
return (sbyte)ReadByte();
}
public byte[] ReadBytes(int count)
{
CheckLength(count);
var temp = new byte[count];
Buffer.BlockCopy(_buffer, _index, temp, 0, count);
_index += count;
return temp;
}
public unsafe short ReadShort()
{
CheckLength(2);
short value;
fixed (byte* ptr = _buffer)
{
value = *(short*)(ptr + _index);
}
_index += 2;
return value;
}
public ushort ReadUShort()
{
return (ushort)ReadShort();
}
public unsafe int ReadInt()
{
CheckLength(4);
int value;
fixed (byte* ptr = _buffer)
{
value = *(int*)(ptr + _index);
}
_index += 4;
return value;
}
public uint ReadUInt()
{
return (uint)ReadInt();
}
public unsafe long ReadLong()
{
CheckLength(8);
long value;
fixed (byte* ptr = _buffer)
{
value = *(long*)(ptr + _index);
}
_index += 8;
return value;
}
public ulong ReadULong()
{
return (ulong)ReadLong();
}
public string ReadString(int count)
{
CheckLength(count);
char[] final = new char[count];
for (int i = 0; i < count; i++)
{
final[i] = (char)ReadByte();
}
return new string(final);
}
public void Skip(int count)
{
CheckLength(count);
_index += count;
}
public override byte[] ToArray()
{
var final = new byte[_buffer.Length];
Buffer.BlockCopy(_buffer, 0, final, 0, _buffer.Length);
return final;
}
}
}

View File

@@ -0,0 +1,167 @@
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace KartExtreme.IO.Packet
{
public class OutPacket : PacketBase, IDisposable
{
private MemoryStream m_stream;
private bool m_disposed;
public override int Length
{
get { return (int)m_stream.Position; }
}
public override int Position
{
get { return (int)m_stream.Position; }
}
public bool Disposed
{
get
{
return m_disposed;
}
}
public OutPacket(int size = 64)
{
m_stream = new MemoryStream(size);
m_disposed = false;
}
//From LittleEndianByteConverter by Shoftee
private void Append(long value, int byteCount)
{
for (int i = 0; i < byteCount; i++)
{
m_stream.WriteByte((byte)value);
value >>= 8;
}
}
public void WriteBool(bool value)
{
ThrowIfDisposed();
WriteByte(value ? (byte)1 : (byte)0);
}
public void WriteByte(byte value = 0)
{
ThrowIfDisposed();
m_stream.WriteByte(value);
}
public void WriteSByte(sbyte value = 0)
{
WriteByte((byte)value);
}
public void WriteBytes(params byte[] value)
{
ThrowIfDisposed();
m_stream.Write(value, 0, value.Length);
}
public void WriteShort(short value = 0)
{
ThrowIfDisposed();
Append(value, 2);
}
public void WriteUShort(ushort value = 0)
{
WriteShort((short)value);
}
public void WriteInt(int value = 0)
{
ThrowIfDisposed();
Append(value, 4);
}
public void WriteUInt(uint value = 0)
{
WriteInt((int)value);
}
public void WriteLong(long value = 0)
{
ThrowIfDisposed();
Append(value, 8);
}
public void WriteULong(ulong value = 0)
{
WriteLong((long)value);
}
public void WriteString(string value)
{
if (value == null)
throw new ArgumentNullException("value");
WriteInt(value.Length);
WriteString(value, value.Length);
}
public void WriteString(string value, int length)
{
if (value == null ||
length < 1 ||
length > value.Length)
throw new ArgumentNullException("value");
var bytes = Encoding.Unicode.GetBytes(value);
var i = 0;
for (; i < value.Length & i < length; i++)
{
var offset = i * 2;
this.WriteByte(bytes[offset]);
this.WriteByte(bytes[offset + 1]);
}
for (; i < length; i++)
{
this.WriteShort();
}
}
public void WriteHexString(string value)
{
if (value == null)
throw new ArgumentNullException("value");
value = value.Replace(" ", "");
for (int i = 0; i < value.Length; i += 2)
{
WriteByte(byte.Parse(value.Substring(i, 2), NumberStyles.HexNumber));
}
}
private void ThrowIfDisposed()
{
if (m_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
public override byte[] ToArray()
{
ThrowIfDisposed();
return m_stream.ToArray();
}
public void Dispose()
{
m_disposed = true;
if (m_stream != null)
m_stream.Dispose();
m_stream = null;
}
}
}

View File

@@ -0,0 +1,25 @@
using System.IO;
using System.Text;
namespace KartExtreme.IO.Packet
{
public abstract class PacketBase
{
public abstract int Length { get; }
public abstract int Position { get; }
public abstract byte[] ToArray();
public override string ToString()
{
var sb = new StringBuilder();
foreach (byte b in this.ToArray())
{
sb.AppendFormat("{0:X2} ", b);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KartExtreme.IO.Packet
{
public sealed class PacketReadException : Exception
{
public PacketReadException(string message)
: base(message)
{
}
}
}

View File

@@ -0,0 +1,9 @@
using System;
namespace KartExtreme.IO
{
public class SettingReadException : Exception
{
public SettingReadException(string key) : base(string.Format("Failed to read setting '{0}'.", key)) { }
}
}

188
trunk/Common/IO/Settings.cs Normal file
View File

@@ -0,0 +1,188 @@
using KartExtreme.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace KartExtreme.IO
{
public static class Settings
{
private const string Comment = "#";
public static string Path { get; private set; }
private static Dictionary<string, string> Dictionary;
public static void Initialize(string path = null)
{
if (path == null)
{
path = "Configuration.ini";
}
if (Settings.Dictionary != null)
{
Settings.Dictionary.Clear();
}
Settings.Path = path;
Settings.Dictionary = new Dictionary<string, string>();
string[] array = Settings.Path.Split('\\');
string name = array[array.Length - 1];
if (!File.Exists(path))
{
throw new FileNotFoundException(string.Format("Unable to find configuration file '{0}'.", name));
}
else
{
string line;
string currentSection = string.Empty;
using (StreamReader file = new StreamReader(path))
{
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith(Settings.Comment))
continue;
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = line.Trim('[', ']');
}
else if (line.Contains("="))
{
Settings.Dictionary.Add(string.Format("{0}{1}{2}",
currentSection,
(currentSection != string.Empty) ? "/" : string.Empty,
line.Split('=')[0]),
line.Split('=')[1].Split(';')[0]);
}
}
}
}
Database.Host = Settings.GetString("Database/Host");
Database.Schema = Settings.GetString("Database/Schema");
Database.Username = Settings.GetString("Database/Username");
Database.Password = Settings.GetString("Database/Password");
}
public static int GetInt(string key, params object[] args)
{
try
{
return int.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static short GetShort(string key, params object[] args)
{
try
{
return short.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static ushort GetUShort(string key, params object[] args)
{
try
{
return ushort.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static byte GetByte(string key, params object[] args)
{
try
{
return byte.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static sbyte GetSByte(string key, params object[] args)
{
try
{
return sbyte.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static bool GetBool(string key, params object[] args)
{
try
{
return bool.Parse(Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
public static string GetString(string key, params object[] args)
{
try
{
return Settings.Dictionary[string.Format(key, args)];
}
catch
{
throw new SettingReadException(key);
}
}
public static IPAddress GetIPAddress(string key, params object[] args)
{
try
{
if (Settings.Dictionary[string.Format(key, args)] == "localhost")
{
return IPAddress.Loopback;
}
else
{
return IPAddress.Parse(Settings.Dictionary[string.Format(key, args)]);
}
}
catch
{
throw new SettingReadException(key);
}
}
public static T GetEnum<T>(string key, params object[] args)
{
try
{
return (T)Enum.Parse(typeof(T), Settings.Dictionary[string.Format(key, args)]);
}
catch
{
throw new SettingReadException(key);
}
}
}
}

294
trunk/Common/IO/lOG.cs Normal file
View File

@@ -0,0 +1,294 @@
using System;
using System.Text;
namespace KartExtreme.IO
{
public static class Log
{
private const byte LabelWidth = 11;
private static bool Entitled = false;
public static bool Running { get; private set; }
public static string Margin
{
get
{
return new string(' ', Log.LabelWidth);
}
}
public static string MaskString(string input, char mask = '*')
{
return new string(mask, input.Length);
}
static Log()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
Log.Running = true;
}
public static string Input(string label)
{
lock (typeof(Log))
{
Log.WriteItem("Input", ConsoleColor.Cyan, string.Empty);
Console.Write(label);
return Console.ReadLine();
}
}
public static string Input(string label, string defaultValue)
{
lock (typeof(Log))
{
Log.WriteItem("Input", ConsoleColor.Cyan, string.Empty);
Console.Write(label);
string result = Console.ReadLine();
if (result == string.Empty)
{
result = defaultValue;
Console.CursorTop--;
Console.CursorLeft = Log.Margin.Length + label.Length;
Console.WriteLine(defaultValue == string.Empty ? "(None)" : result);
}
return result;
}
}
/// <summary>
/// Writes a labeled item to the output.
/// </summary>
/// <param name="label">The label</param>
/// <param name="labelColor">The label's color</param>
/// <param name="value">The text</param>
/// <param name="args">Arguments</param>
private static void WriteItem(string label, ConsoleColor labelColor, string value, params object[] args)
{
lock (typeof(Log))
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', Log.LabelWidth - label.Length - 3);
sb.Append("[");
sb.Append(label);
sb.Append("]");
sb.Append(" ");
label = sb.ToString();
value = string.Format(value, args);
Console.ForegroundColor = labelColor;
Console.Write(label);
Console.ForegroundColor = ConsoleColor.Gray;
bool first = true;
foreach (string s in value.Split('\n'))
{
string[] lines = new string[(int)Math.Ceiling((float)s.Length / (float)(Console.BufferWidth - Log.LabelWidth))];
for (int i = 0; i < lines.Length; i++)
{
if (i == lines.Length - 1)
{
lines[i] = s.Substring((Console.BufferWidth - Log.LabelWidth) * i);
}
else
{
lines[i] = s.Substring((Console.BufferWidth - Log.LabelWidth) * i, (Console.BufferWidth - Log.LabelWidth));
}
}
foreach (string line in lines)
{
if (!first)
{
Console.Write(Log.Margin);
}
if ((line.Length + Log.LabelWidth) < Console.BufferWidth)
{
Console.WriteLine(line);
}
else if ((line.Length + Log.LabelWidth) == Console.BufferWidth)
{
Console.Write(line);
}
first = false;
}
}
}
}
public static void SkipLine()
{
Console.WriteLine();
}
public static void Entitle(string value, params object[] args)
{
lock (typeof(Log))
{
Console.ForegroundColor = ConsoleColor.Yellow;
StringBuilder sb = new StringBuilder();
sb.Append("\n");
//for (int i = 0; i < Console.WindowWidth / 2 - value.Length / 2; i++)
//{
// sb.Append(' ');
//}
sb.Append('\t');
sb.Append((Log.Entitled ? "" : "") + string.Format(value, args) + '\n');
Console.WriteLine(sb.ToString());
Console.ForegroundColor = ConsoleColor.Gray;
Console.Title = string.Format(value, args);
Log.Entitled = true;
}
}
public static void Inform(string value, params object[] args)
{
Log.WriteItem("Info", ConsoleColor.White, value, args);
}
public static void Inform(object value)
{
Log.Inform(value.ToString());
}
public static void Warn(string value, params object[] args)
{
Log.WriteItem("Warning", ConsoleColor.Yellow, value, args);
}
public static void Warn(object value)
{
Log.Warn(value.ToString());
}
public static void Error(string value, params object[] args)
{
Log.WriteItem("Error", ConsoleColor.Red, value, args);
}
public static bool ShowStackTrace { get; set; }
public static void Error(Exception exception)
{
Log.WriteItem("Error", ConsoleColor.Red, Log.ShowStackTrace ? exception.ToString() : exception.Message);
}
public static void Error(string label, Exception exception, params object[] args)
{
Log.WriteItem("Error", ConsoleColor.Red, "{0}\n{1}", string.Format(label, args), Log.ShowStackTrace ? exception.ToString() : exception.Message);
}
public static void Debug(string value, params object[] args)
{
Log.WriteItem("Debug", ConsoleColor.Green, value, args);
}
public static void Success(object value)
{
Log.Debug(value.ToString());
}
public static void Sql(string value, params object[] args)
{
Log.WriteItem("Sql", ConsoleColor.Magenta, value, args);
}
public static void Hex(string label, byte[] value, params object[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format(label, args));
sb.Append('\n');
if (value == null || value.Length == 0)
{
sb.Append("(Empty)");
}
else
{
int lineSeparation = 0;
foreach (byte b in value)
{
if (lineSeparation == 16)
{
sb.Append('\n');
lineSeparation = 0;
}
sb.AppendFormat("{0:X2} ", b);
lineSeparation++;
}
}
Log.WriteItem("Hex", ConsoleColor.Magenta, sb.ToString());
}
public static void Hex(string label, byte b, params object[] args)
{
Log.Hex(label, new byte[] { b }, args);
}
public static void Quit()
{
Log.Running = false;
Log.Inform("Press any key to quit . . .");
Console.Read();
}
public static LoadingIndicator Load(string header)
{
return new LoadingIndicator(header);
}
}
public class LoadingIndicator : IDisposable
{
public static bool ShowTime { get; set; }
private DateTime LoadStartTime { get; set; }
internal LoadingIndicator(string header)
{
lock (typeof(Log))
{
Console.Write("{0} {1}... ", Log.Margin, header);
}
}
public void Dispose()
{
lock (typeof(Log))
{
if (LoadingIndicator.ShowTime)
{
Console.WriteLine("({0}ms)", (DateTime.Now - this.LoadStartTime).Milliseconds);
}
else
{
Console.WriteLine();
}
}
}
}
}