Initial Commit

This commit is contained in:
SnapixLP | Tim G.
2025-05-19 09:16:34 +02:00
commit c214be937c
39 changed files with 3710 additions and 0 deletions

352
Server/.gitignore vendored Normal file
View File

@@ -0,0 +1,352 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
/.dotnet
/.packages
/.tools/vswhere/2.5.2
/.tools/native/iltools
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Exceptions to the exclusions
!src/Microsoft.DotNet.Wpf/src/WpfGfx/codegen/mcg/main/*.rsp
!src/Microsoft.DotNet.Wpf/src/WpfGfx/tools/csp/**/*.rsp

54
Server/BackendServer.cs Normal file
View File

@@ -0,0 +1,54 @@
using System.Net.Sockets;
using DX86.Modules;
namespace Server;
public class BackendServer : DX86.TcpServer
{
CommandManager _CommandManager;
public BackendServer(string address, int port, MessageSender ms) : base(address, port, ms)
{
ms.Log("[BACKENDSERVER] Setting up server.");
_CommandManager = new CommandManager();
ms.Log("[BACKENDSERVER] Server Setup Complete.");
}
public override string ToggleOption(string option, string value)
{
throw new NotImplementedException();
}
public override List<List<string>> ConfigureOptions(string option)
{
throw new NotImplementedException();
}
protected override void ClientConnectEvent(TcpClient client)
{
ms.Log("[BACKENDSERVER] Client connected: " + client.Client.RemoteEndPoint);
}
protected override void MessageReceivedEvent(TcpClient client, string message)
{
ms.Log("[BACKENDSERVER] Message received from client: " + message);
if (message.StartsWith("."))
{
handleCommand(cmd: message, client: client);
}
}
protected override void ClientDisconnectEvent(TcpClient client)
{
throw new NotImplementedException();
}
private void handleCommand(string cmd, TcpClient client)
{
string[] args = cmd.Split(' ');
string command = args[0].Substring(1); // Remove the leading dot
string[] commandArgs = args.Skip(1).ToArray(); // Get the arguments after the command
}
}

44
Server/CommandManager.cs Normal file
View File

@@ -0,0 +1,44 @@
using System.Reflection;
using Server.Commands;
namespace Server;
public class CommandManager
{
private readonly Dictionary<string, ICommand> _commands = new();
public CommandManager()
{
LoadCommands();
}
private void LoadCommands()
{
// Get all types implementing ICommand
var commandTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(ICommand).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
foreach (var type in commandTypes)
{
// Create an instance of the command
if (Activator.CreateInstance(type) is ICommand command)
{
// Use the Executor property as the key
_commands[command.Executor] = command;
}
}
}
public void ExecuteCommand(string executor, params string[] args)
{
if (_commands.TryGetValue(executor, out var command))
{
command.Exec(args);
}
else
{
Console.WriteLine($"Command '{executor}' not found.");
}
}
}

View File

@@ -0,0 +1,10 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public interface ICommand
{
string Executor { get; }
public void Exec(string[] args, TcpClient? client = null, TcpServer? clientSocket = null);
}

242
Server/MySQL.cs Normal file
View File

@@ -0,0 +1,242 @@
using System;
using System.Collections.Generic;
using System.Data;
using DX86.Modules;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
namespace Server
{
public class MySQL
{
private MySqlConnection _connection;
private MessageSender ms;
public MySQL(string username, string password, string server, string database, MessageSender ms)
{
this.ms = ms;
ms.Log("[MySQL] Initializing connection...");
string connectionString = $"Server={server};Database={database};User ID={username};Password={password};";
_connection = new MySqlConnection(connectionString);
ms.Log("[MySQL] Connection to database...");
try
{
_connection.Open();
ms.Log("[MySQL] Connection established.");
}
catch (Exception ex)
{
ms.Error("[MySQL] Connection failed: " + ex.Message);
ms.Error("[MySQL] Please check your connection settings.");
ms.Error("[MySQL] Make sure the MySQL server is running and accessible.");
ms.Error("[MySQL] A MySQL Connection is necessary to run this application.");
ms.Error("[MySQL] Exiting...");
Environment.Exit(1);
}
}
private string JsonResponse(object data, bool error = false)
{
return JsonConvert.SerializeObject(new { error, data });
}
private string GetType(object value)
{
return value switch
{
int => "i",
float or double => "d",
string => "s",
_ => "b"
};
}
public string Insert(string table, Dictionary<string, object> data)
{
string columns = string.Join(", ", data.Keys);
string placeholders = string.Join(", ", new string[data.Count].Select(_ => "?"));
string sql = $"INSERT INTO `{table}` ({columns}) VALUES ({placeholders})";
using var cmd = new MySqlCommand(sql, _connection);
string types = "";
foreach (var value in data.Values)
{
types += GetType(value);
cmd.Parameters.AddWithValue(null, value);
}
try
{
cmd.ExecuteNonQuery();
long insertId = cmd.LastInsertedId;
return JsonResponse(new { insert_id = insertId });
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Get(string table, Dictionary<string, object> parameters = null, int? limit = null, int? offset = null)
{
string sql = $"SELECT * FROM `{table}`";
string types = "";
var values = new List<object>();
if (parameters != null && parameters.Count > 0)
{
var conditions = new List<string>();
foreach (var param in parameters)
{
conditions.Add($"`{param.Key}` = ?");
types += GetType(param.Value);
values.Add(param.Value);
}
sql += " WHERE " + string.Join(" AND ", conditions);
}
if (limit.HasValue)
{
sql += " LIMIT ?";
types += "i";
values.Add(limit.Value);
if (offset.HasValue)
{
sql += " OFFSET ?";
types += "i";
values.Add(offset.Value);
}
}
using var cmd = new MySqlCommand(sql, _connection);
for (int i = 0; i < values.Count; i++)
{
cmd.Parameters.AddWithValue(null, values[i]);
}
try
{
using var reader = cmd.ExecuteReader();
var data = new List<Dictionary<string, object>>();
while (reader.Read())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
data.Add(row);
}
return JsonResponse(data);
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Update(string table, Dictionary<string, object> data, Dictionary<string, object> where)
{
var setClauses = new List<string>();
var whereClauses = new List<string>();
string types = "";
var values = new List<object>();
foreach (var item in data)
{
setClauses.Add($"`{item.Key}` = ?");
types += GetType(item.Value);
values.Add(item.Value);
}
foreach (var condition in where)
{
whereClauses.Add($"`{condition.Key}` = ?");
types += GetType(condition.Value);
values.Add(condition.Value);
}
string sql = $"UPDATE `{table}` SET {string.Join(", ", setClauses)} WHERE {string.Join(" AND ", whereClauses)}";
using var cmd = new MySqlCommand(sql, _connection);
for (int i = 0; i < values.Count; i++)
{
cmd.Parameters.AddWithValue(null, values[i]);
}
try
{
int affectedRows = cmd.ExecuteNonQuery();
return JsonResponse(new { affected_rows = affectedRows });
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Delete(string table, Dictionary<string, object> where)
{
var whereClauses = new List<string>();
string types = "";
var values = new List<object>();
foreach (var condition in where)
{
whereClauses.Add($"`{condition.Key}` = ?");
types += GetType(condition.Value);
values.Add(condition.Value);
}
string sql = $"DELETE FROM `{table}` WHERE {string.Join(" AND ", whereClauses)}";
using var cmd = new MySqlCommand(sql, _connection);
for (int i = 0; i < values.Count; i++)
{
cmd.Parameters.AddWithValue(null, values[i]);
}
try
{
int affectedRows = cmd.ExecuteNonQuery();
return JsonResponse(new { affected_rows = affectedRows });
}
catch (Exception ex)
{
return JsonResponse($"Execute failed: {ex.Message}", true);
}
}
public string Query(string sql, string types = null, List<object> values = null)
{
using var cmd = new MySqlCommand(sql, _connection);
if (types != null && values != null)
{
for (int i = 0; i < values.Count; i++)
{
cmd.Parameters.AddWithValue(null, values[i]);
}
}
try
{
using var reader = cmd.ExecuteReader();
var data = new List<Dictionary<string, object>>();
while (reader.Read())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
data.Add(row);
}
return JsonResponse(data);
}
catch (Exception ex)
{
return JsonResponse($"Query failed: {ex.Message}", true);
}
}
}
}

34
Server/Program.cs Normal file
View File

@@ -0,0 +1,34 @@
using DX86.Modules;
using Library;
namespace Server;
class Program
{
public static MessageSender messageSender;
public static MessageBox messageBox;
public static InputBox inputBox;
public static ItemSelector itemSelector;
public static MySQL mySql;
static void Main(string[] args)
{
Console.WriteLine("Initializing server...");
// Initialize the server components
messageSender = new MessageSender("log.txt");
messageBox = new MessageBox(messageSender);
inputBox = new InputBox(messageSender);
itemSelector = new ItemSelector(messageSender);
// Connect to the database
//mySql = new MySQL("username", "password", "localhost", "database", messageSender);
// Start the server
messageBox.ShowAsync("Server started", ["LOL","Laurenz Stinkt xd"]);
string name = inputBox.ShowAsync("Test", ["type your name "]);
messageBox.ShowAsync("Welcome", ["Hello " + name]);
}
}

20
Server/Server.csproj Normal file
View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DX86\DX86.csproj" />
<ProjectReference Include="..\Library\Library.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MySql.Data" Version="9.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>