From 70cfb69fc2259b94dc2a20e0188d27216f3dda57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Boh=C3=A1=C4=8Dek?= Date: Tue, 28 Dec 2021 13:15:41 +0100 Subject: [PATCH] chore: fix line endings --- .gitignore | 1358 ++++++++--------- .../Client/BaseNostaleClient.cs | 146 +- Core/NosSmooth.Core/Client/INostaleClient.cs | 140 +- .../Commands/CommandProcessor.cs | 140 +- Core/NosSmooth.Core/Commands/ICommand.cs | 38 +- .../Commands/ICommandHandler.cs | 66 +- Core/NosSmooth.Core/Commands/WalkCommand.cs | 30 +- .../Errors/CommandHandlerNotFound.cs | 32 +- .../Extensions/ServiceCollectionExtensions.cs | 368 ++--- Core/NosSmooth.Core/IsExternalInit.cs | 28 +- Core/NosSmooth.Core/NosSmooth.Core.csproj | 36 +- .../Converters/ISpecificPacketSerializer.cs | 262 ++-- .../Packets/Converters/InPacketSerializer.cs | 180 +-- Core/NosSmooth.Core/Packets/IPacketHandler.cs | 70 +- .../Packets/IPacketResponder.cs | 102 +- .../Packets/IPacketSerializer.cs | 86 +- Core/NosSmooth.Core/Packets/PacketHandler.cs | 206 +-- .../Packets/PacketSerializer.cs | 174 +-- .../Packets/PacketSerializerProvider.cs | 164 +- .../Packets/ParsingFailedPacket.cs | 72 +- .../Events/GMJoinedMap.cs | 12 +- .../NosSmooth.Extensions.csproj | 26 +- .../Events/Handlers/EventDispatcher.cs | 100 +- .../Events/Handlers/IGameResponder.cs | 66 +- .../Extensions/ServiceCollectionExtensions.cs | 86 +- Core/NosSmooth.Game/NosSmooth.Game.csproj | 20 +- .../NosSmooth.Language.csproj | 20 +- DllExport.bat | 1016 ++++++------ .../Walk/Errors/WalkNotFinishedError.cs | 34 +- .../CommandHandlers/Walk/WalkCancelReason.cs | 68 +- .../Walk/WalkCommandHandler.cs | 188 +-- .../Walk/WalkCommandHandlerOptions.cs | 74 +- .../Walk/WalkPacketResponder.cs | 118 +- .../CommandHandlers/Walk/WalkStatus.cs | 352 ++--- .../Extensions/ServiceCollectionExtensions.cs | 82 +- .../Hooks/NostaleHookManager.cs | 146 +- .../Hooks/WalkEventArgs.cs | 66 +- .../IPacketInterceptor.cs | 54 +- .../LocalClientOptions.cs | 86 +- .../NosSmooth.LocalClient.csproj | 38 +- .../NostaleLocalClient.cs | 422 ++--- Local/NosSmooth.LocalClient/NostaleWindow.cs | 114 +- Local/NosSmooth.LocalCore/Character.cpp | 56 +- Local/NosSmooth.LocalCore/Character.h | 74 +- .../CharacterUnmanaged.cpp | 236 +-- .../NosSmooth.LocalCore/CharacterUnmanaged.h | 112 +- Local/NosSmooth.LocalCore/ModuleHook.cpp | 96 +- Local/NosSmooth.LocalCore/ModuleHook.h | 38 +- Local/NosSmooth.LocalCore/ModuleHook.ixx | 4 +- Local/NosSmooth.LocalCore/Network.cpp | 84 +- Local/NosSmooth.LocalCore/Network.h | 92 +- .../NosSmooth.LocalCore/NetworkUnmanaged.cpp | 340 ++--- Local/NosSmooth.LocalCore/NetworkUnmanaged.h | 124 +- .../NosSmooth.LocalCore.vcxproj | 394 ++--- .../NosSmooth.LocalCore.vcxproj.filters | 126 +- Local/NosSmooth.LocalCore/NosSmoothCore.cpp | 66 +- Local/NosSmooth.LocalCore/NosSmoothCore.h | 46 +- Local/NosSmooth.LocalCore/NostaleString.h | 206 +-- Local/NosSmooth.LocalCore/packages.config | 6 +- Remote/NosSmooth.Cryptography/IDecryptor.cs | 10 +- Remote/NosSmooth.Cryptography/IEncryptor.cs | 10 +- .../NosSmooth.Cryptography.csproj | 18 +- .../NosSmooth.Cryptography/WorldDecryptor.cs | 10 +- .../NosSmooth.Cryptography/WorldEncryptor.cs | 10 +- .../NosSmooth.RemoteClient.csproj | 104 +- .../Properties/AssemblyInfo.cs | 68 +- Samples/DamageCounter/App.xaml | 18 +- Samples/DamageCounter/App.xaml.cs | 32 +- Samples/DamageCounter/AssemblyInfo.cs | 18 +- Samples/DamageCounter/DamageCounter.csproj | 20 +- Samples/DamageCounter/MainWindow.xaml | 24 +- Samples/DamageCounter/MainWindow.xaml.cs | 54 +- Samples/InterceptNameChanger/DllMain.cs | 12 +- Samples/InterceptNameChanger/FodyWeavers.xml | 4 +- .../InterceptNameChanger.csproj | 132 +- .../PacketInterceptor/DummyNostaleClient.cs | 74 +- .../PacketInterceptor.csproj | 30 +- Samples/PacketInterceptor/Program.cs | 82 +- Samples/PacketInterceptor/TestResponder.cs | 42 +- Samples/PacketLogger/App.xaml | 18 +- Samples/PacketLogger/App.xaml.cs | 32 +- Samples/PacketLogger/AssemblyInfo.cs | 18 +- Samples/PacketLogger/MainWindow.xaml | 24 +- Samples/PacketLogger/MainWindow.xaml.cs | 54 +- Samples/PacketLogger/PacketLogger.csproj | 36 +- .../Packets/PacketLoggerResponder.cs | 52 +- Samples/SimpleChat/DllMain.cs | 8 +- Samples/SimpleChat/FodyWeavers.xml | 6 +- Samples/SimpleChat/SimpleChat.csproj | 132 +- Samples/WalkCommands/ChatPacketInterceptor.cs | 210 +-- .../WalkCommands/Commands/DetachCommand.cs | 104 +- Samples/WalkCommands/Commands/WalkCommands.cs | 152 +- Samples/WalkCommands/DllMain.cs | 78 +- Samples/WalkCommands/FodyWeavers.xml | 4 +- Samples/WalkCommands/Startup.cs | 100 +- Samples/WalkCommands/WalkCommands.csproj | 150 +- .../NosSmooth.Core.Tests.csproj | 54 +- .../Packets/InPacketSerializerTest.cs | 314 ++-- 98 files changed, 5652 insertions(+), 5652 deletions(-) diff --git a/.gitignore b/.gitignore index b3f5c28..681290b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,679 +1,679 @@ - -# Created by https://www.toptal.com/developers/gitignore/api/csharp,c++,visualstudio,rider -# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,c++,visualstudio,rider - -### C++ ### -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -### Csharp ### -## 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 -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# 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 -nunit-*.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/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.iobj -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.tlog -*.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 - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# 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 -# NuGet Symbol Packages -*.snupkg -# 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 - -# Nuget personal access tokens and Credentials -# nuget.config - -# 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 -*.appxbundle -*.appxupload - -# 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 -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# 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/ - -# CodeRush personal settings -.cr/personal - -# 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/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd - -# VS Code files for those working on multiple tools -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -*.code-workspace - -# Local History for Visual Studio Code -.history/ - -# Windows Installer files from build outputs -*.cab -*.msi -*.msix -*.msm -*.msp - -# JetBrains Rider -.idea/ -*.sln.iml - -### Rider ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/**/usage.statistics.xml -.idea/**/dictionaries -.idea/**/shelf - -# AWS User-specific -.idea/**/aws.xml - -# Generated files -.idea/**/contentModel.xml - -# Sensitive or high-churn files -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml -.idea/**/dbnavigator.xml - -# Gradle -.idea/**/gradle.xml -.idea/**/libraries - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/artifacts -# .idea/compiler.xml -# .idea/jarRepositories.xml -# .idea/modules.xml -# .idea/*.iml -# .idea/modules -# *.iml -# *.ipr - -# CMake -cmake-build-*/ - -# Mongo Explorer plugin -.idea/**/mongoSettings.xml - -# File-based project format -*.iws - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -# Editor-based Rest Client -.idea/httpRequests - -# Android studio 3.1+ serialized cache file -.idea/caches/build_file_checksums.ser - -### VisualStudio ### - -# User-specific files - -# User-specific files (MonoDevelop/Xamarin Studio) - -# Mono auto generated files - -# Build results - -# Visual Studio 2015/2017 cache/options directory -# Uncomment if you have tasks that create the project's static files in wwwroot - -# Visual Studio 2017 auto generated files - -# MSTest test Results - -# NUnit - -# Build Results of an ATL Project - -# Benchmark Results - -# .NET Core - -# ASP.NET Scaffolding - -# StyleCop - -# Files built by Visual Studio - -# Chutzpah Test files - -# Visual C++ cache files - -# Visual Studio profiler - -# Visual Studio Trace Files - -# TFS 2012 Local Workspace - -# Guidance Automation Toolkit - -# ReSharper is a .NET coding add-in - -# TeamCity is a build add-in - -# DotCover is a Code Coverage Tool - -# AxoCover is a Code Coverage Tool - -# Coverlet is a free, cross platform Code Coverage Tool - -# Visual Studio code coverage results - -# NCrunch - -# MightyMoose - -# Web workbench (sass) - -# Installshield output folder - -# DocProject is a documentation generator add-in - -# Click-Once directory - -# Publish Web Output -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted - -# 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 - -# NuGet Packages -# NuGet Symbol Packages -# The packages folder can be ignored because of Package Restore -# except build/, which is used as an MSBuild target. -# Uncomment if necessary however generally it will be regenerated when needed -# NuGet v3's project.json files produces more ignorable files - -# Nuget personal access tokens and Credentials -# nuget.config - -# Microsoft Azure Build Output - -# Microsoft Azure Emulator - -# Windows Store app package directories and files - -# Visual Studio cache files -# files ending in .cache can be ignored -# but keep track of directories ending in .cache - -# Others - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) - -# RIA/Silverlight projects - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) - -# SQL Server files - -# Business Intelligence projects - -# Microsoft Fakes - -# GhostDoc plugin setting file - -# Node.js Tools for Visual Studio - -# Visual Studio 6 build log - -# Visual Studio 6 workspace options file - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) - -# Visual Studio LightSwitch build output - -# Paket dependency manager - -# FAKE - F# Make - -# CodeRush personal settings - -# Python Tools for Visual Studio (PTVS) - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio - -# Telerik's JustMock configuration file - -# BizTalk build output - -# OpenCover UI analysis results - -# Azure Stream Analytics local run output - -# MSBuild Binary and Structured Log - -# NVidia Nsight GPU debugger configuration file - -# MFractors (Xamarin productivity tool) working folder - -# Local History for Visual Studio - -# BeatPulse healthcheck temp database - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 - -# Ionide (cross platform F# VS Code tools) working folder - -# Fody - auto-generated XML schema - -# VS Code files for those working on multiple tools - -# Local History for Visual Studio Code - -# Windows Installer files from build outputs - -# JetBrains Rider - -### VisualStudio Patch ### -# Additional files built by Visual Studio - -# End of https://www.toptal.com/developers/gitignore/api/csharp,c++,visualstudio,rider + +# Created by https://www.toptal.com/developers/gitignore/api/csharp,c++,visualstudio,rider +# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,c++,visualstudio,rider + +### C++ ### +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +### Csharp ### +## 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 +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# 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 +nunit-*.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/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.iobj +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.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 + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# 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 +# NuGet Symbol Packages +*.snupkg +# 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 + +# Nuget personal access tokens and Credentials +# nuget.config + +# 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 +*.appxbundle +*.appxupload + +# 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 +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# 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/ + +# CodeRush personal settings +.cr/personal + +# 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/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +.idea/ +*.sln.iml + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudio ### + +# User-specific files + +# User-specific files (MonoDevelop/Xamarin Studio) + +# Mono auto generated files + +# Build results + +# Visual Studio 2015/2017 cache/options directory +# Uncomment if you have tasks that create the project's static files in wwwroot + +# Visual Studio 2017 auto generated files + +# MSTest test Results + +# NUnit + +# Build Results of an ATL Project + +# Benchmark Results + +# .NET Core + +# ASP.NET Scaffolding + +# StyleCop + +# Files built by Visual Studio + +# Chutzpah Test files + +# Visual C++ cache files + +# Visual Studio profiler + +# Visual Studio Trace Files + +# TFS 2012 Local Workspace + +# Guidance Automation Toolkit + +# ReSharper is a .NET coding add-in + +# TeamCity is a build add-in + +# DotCover is a Code Coverage Tool + +# AxoCover is a Code Coverage Tool + +# Coverlet is a free, cross platform Code Coverage Tool + +# Visual Studio code coverage results + +# NCrunch + +# MightyMoose + +# Web workbench (sass) + +# Installshield output folder + +# DocProject is a documentation generator add-in + +# Click-Once directory + +# Publish Web Output +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted + +# 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 + +# NuGet Packages +# NuGet Symbol Packages +# The packages folder can be ignored because of Package Restore +# except build/, which is used as an MSBuild target. +# Uncomment if necessary however generally it will be regenerated when needed +# NuGet v3's project.json files produces more ignorable files + +# Nuget personal access tokens and Credentials +# nuget.config + +# Microsoft Azure Build Output + +# Microsoft Azure Emulator + +# Windows Store app package directories and files + +# Visual Studio cache files +# files ending in .cache can be ignored +# but keep track of directories ending in .cache + +# Others + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) + +# RIA/Silverlight projects + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) + +# SQL Server files + +# Business Intelligence projects + +# Microsoft Fakes + +# GhostDoc plugin setting file + +# Node.js Tools for Visual Studio + +# Visual Studio 6 build log + +# Visual Studio 6 workspace options file + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) + +# Visual Studio LightSwitch build output + +# Paket dependency manager + +# FAKE - F# Make + +# CodeRush personal settings + +# Python Tools for Visual Studio (PTVS) + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio + +# Telerik's JustMock configuration file + +# BizTalk build output + +# OpenCover UI analysis results + +# Azure Stream Analytics local run output + +# MSBuild Binary and Structured Log + +# NVidia Nsight GPU debugger configuration file + +# MFractors (Xamarin productivity tool) working folder + +# Local History for Visual Studio + +# BeatPulse healthcheck temp database + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 + +# Ionide (cross platform F# VS Code tools) working folder + +# Fody - auto-generated XML schema + +# VS Code files for those working on multiple tools + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/csharp,c++,visualstudio,rider diff --git a/Core/NosSmooth.Core/Client/BaseNostaleClient.cs b/Core/NosSmooth.Core/Client/BaseNostaleClient.cs index 9ba0813..c146d7b 100644 --- a/Core/NosSmooth.Core/Client/BaseNostaleClient.cs +++ b/Core/NosSmooth.Core/Client/BaseNostaleClient.cs @@ -1,74 +1,74 @@ -// -// BaseNostaleClient.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading; -using System.Threading.Tasks; -using NosCore.Packets.Interfaces; -using NosSmooth.Core.Commands; -using NosSmooth.Core.Packets; -using Remora.Results; - -namespace NosSmooth.Core.Client; - -/// -/// Represents base class of . -/// -/// -/// This class serializes packets and processes commands. -/// -public abstract class BaseNostaleClient : INostaleClient -{ - private readonly CommandProcessor _commandProcessor; - private readonly IPacketSerializer _packetSerializer; - - /// - /// Initializes a new instance of the class. - /// - /// The command processor. - /// The packet serializer. - protected BaseNostaleClient - ( - CommandProcessor commandProcessor, - IPacketSerializer packetSerializer - ) - { - _commandProcessor = commandProcessor; - _packetSerializer = packetSerializer; - } - - /// - public abstract Task RunAsync(CancellationToken stopRequested = default); - - /// - public virtual Task SendPacketAsync(IPacket packet, CancellationToken ct = default) - { - var serialized = _packetSerializer.Serialize(packet); - - return serialized.IsSuccess - ? SendPacketAsync(serialized.Entity, ct) - : Task.FromResult(Result.FromError(serialized)); - } - - /// - public abstract Task SendPacketAsync(string packetString, CancellationToken ct = default); - - /// - public abstract Task ReceivePacketAsync(string packetString, CancellationToken ct = default); - - /// - public virtual Task ReceivePacketAsync(IPacket packet, CancellationToken ct = default) - { - var serialized = _packetSerializer.Serialize(packet); - - return serialized.IsSuccess - ? ReceivePacketAsync(serialized.Entity, ct) - : Task.FromResult(Result.FromError(serialized)); - } - - /// - public Task SendCommandAsync(ICommand command, CancellationToken ct = default) => - _commandProcessor.ProcessCommand(command, ct); +// +// BaseNostaleClient.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading; +using System.Threading.Tasks; +using NosCore.Packets.Interfaces; +using NosSmooth.Core.Commands; +using NosSmooth.Core.Packets; +using Remora.Results; + +namespace NosSmooth.Core.Client; + +/// +/// Represents base class of . +/// +/// +/// This class serializes packets and processes commands. +/// +public abstract class BaseNostaleClient : INostaleClient +{ + private readonly CommandProcessor _commandProcessor; + private readonly IPacketSerializer _packetSerializer; + + /// + /// Initializes a new instance of the class. + /// + /// The command processor. + /// The packet serializer. + protected BaseNostaleClient + ( + CommandProcessor commandProcessor, + IPacketSerializer packetSerializer + ) + { + _commandProcessor = commandProcessor; + _packetSerializer = packetSerializer; + } + + /// + public abstract Task RunAsync(CancellationToken stopRequested = default); + + /// + public virtual Task SendPacketAsync(IPacket packet, CancellationToken ct = default) + { + var serialized = _packetSerializer.Serialize(packet); + + return serialized.IsSuccess + ? SendPacketAsync(serialized.Entity, ct) + : Task.FromResult(Result.FromError(serialized)); + } + + /// + public abstract Task SendPacketAsync(string packetString, CancellationToken ct = default); + + /// + public abstract Task ReceivePacketAsync(string packetString, CancellationToken ct = default); + + /// + public virtual Task ReceivePacketAsync(IPacket packet, CancellationToken ct = default) + { + var serialized = _packetSerializer.Serialize(packet); + + return serialized.IsSuccess + ? ReceivePacketAsync(serialized.Entity, ct) + : Task.FromResult(Result.FromError(serialized)); + } + + /// + public Task SendCommandAsync(ICommand command, CancellationToken ct = default) => + _commandProcessor.ProcessCommand(command, ct); } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Client/INostaleClient.cs b/Core/NosSmooth.Core/Client/INostaleClient.cs index 7abb15c..f223f4a 100644 --- a/Core/NosSmooth.Core/Client/INostaleClient.cs +++ b/Core/NosSmooth.Core/Client/INostaleClient.cs @@ -1,71 +1,71 @@ -// -// INostaleClient.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading; -using System.Threading.Tasks; -using NosCore.Packets.Interfaces; -using NosSmooth.Core.Commands; -using Remora.Results; - -namespace NosSmooth.Core.Client; - -/// -/// Class representing nostale client that may send and receive packets as well as process commands. -/// -public interface INostaleClient -{ - /// - /// Starts the client. - /// - /// A cancellation token for stopping the client. - /// The result that may or may not have succeeded. - public Task RunAsync(CancellationToken stopRequested = default); - - /// - /// Sends the given packet to the server. - /// - /// The packet to send. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task SendPacketAsync(IPacket packet, CancellationToken ct = default); - - /// - /// Sends the given raw packet string. - /// - /// The packed string to send in plain text. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task SendPacketAsync(string packetString, CancellationToken ct = default); - - /// - /// Receives the given raw packet string. - /// - /// The packet to receive in plain text. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task ReceivePacketAsync(string packetString, CancellationToken ct = default); - - /// - /// Receives the given packet. - /// - /// The packet to receive. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task ReceivePacketAsync(IPacket packet, CancellationToken ct = default); - - /// - /// Sends the given command to the client. - /// - /// - /// Commands can be used for doing complex operations like walking that require sending multiple packets - /// and/or calling some functions of the local client. - /// This method will not return until the command is finished or it failed. - /// - /// The command to send. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task SendCommandAsync(ICommand command, CancellationToken ct = default); +// +// INostaleClient.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading; +using System.Threading.Tasks; +using NosCore.Packets.Interfaces; +using NosSmooth.Core.Commands; +using Remora.Results; + +namespace NosSmooth.Core.Client; + +/// +/// Class representing nostale client that may send and receive packets as well as process commands. +/// +public interface INostaleClient +{ + /// + /// Starts the client. + /// + /// A cancellation token for stopping the client. + /// The result that may or may not have succeeded. + public Task RunAsync(CancellationToken stopRequested = default); + + /// + /// Sends the given packet to the server. + /// + /// The packet to send. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task SendPacketAsync(IPacket packet, CancellationToken ct = default); + + /// + /// Sends the given raw packet string. + /// + /// The packed string to send in plain text. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task SendPacketAsync(string packetString, CancellationToken ct = default); + + /// + /// Receives the given raw packet string. + /// + /// The packet to receive in plain text. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task ReceivePacketAsync(string packetString, CancellationToken ct = default); + + /// + /// Receives the given packet. + /// + /// The packet to receive. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task ReceivePacketAsync(IPacket packet, CancellationToken ct = default); + + /// + /// Sends the given command to the client. + /// + /// + /// Commands can be used for doing complex operations like walking that require sending multiple packets + /// and/or calling some functions of the local client. + /// This method will not return until the command is finished or it failed. + /// + /// The command to send. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task SendCommandAsync(ICommand command, CancellationToken ct = default); } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Commands/CommandProcessor.cs b/Core/NosSmooth.Core/Commands/CommandProcessor.cs index 4bb42cd..37a492e 100644 --- a/Core/NosSmooth.Core/Commands/CommandProcessor.cs +++ b/Core/NosSmooth.Core/Commands/CommandProcessor.cs @@ -1,71 +1,71 @@ -// -// CommandProcessor.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using NosSmooth.Core.Errors; -using Remora.Results; - -namespace NosSmooth.Core.Commands; - -/// -/// Calls for the executing command -/// by using dependency injection. -/// -public class CommandProcessor -{ - private readonly IServiceProvider _provider; - - /// - /// Initializes a new instance of the class. - /// - /// The dependency injection provider. - public CommandProcessor(IServiceProvider provider) - { - _provider = provider; - } - - /// - /// Processes the given command, calling its handler or returning error. - /// - /// The command to process. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - /// Thrown on critical error. - public Task ProcessCommand(ICommand command, CancellationToken ct = default) - { - var processMethod = GetType().GetMethod - ( - nameof(DispatchCommandHandler), - BindingFlags.NonPublic | BindingFlags.Instance - ); - - if (processMethod is null) - { - throw new InvalidOperationException("Could not find process command generic method in command processor."); - } - - var boundProcessMethod = processMethod.MakeGenericMethod(command.GetType()); - - return (Task)boundProcessMethod.Invoke(this, new object[] { command, ct })!; - } - - private Task DispatchCommandHandler(TCommand command, CancellationToken ct = default) - where TCommand : class, ICommand - { - using var scope = _provider.CreateScope(); - var commandHandler = scope.ServiceProvider.GetService>(); - if (commandHandler is null) - { - return Task.FromResult(Result.FromError(new CommandHandlerNotFound(command.GetType()))); - } - - return commandHandler.HandleCommand(command, ct); - } +// +// CommandProcessor.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using NosSmooth.Core.Errors; +using Remora.Results; + +namespace NosSmooth.Core.Commands; + +/// +/// Calls for the executing command +/// by using dependency injection. +/// +public class CommandProcessor +{ + private readonly IServiceProvider _provider; + + /// + /// Initializes a new instance of the class. + /// + /// The dependency injection provider. + public CommandProcessor(IServiceProvider provider) + { + _provider = provider; + } + + /// + /// Processes the given command, calling its handler or returning error. + /// + /// The command to process. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + /// Thrown on critical error. + public Task ProcessCommand(ICommand command, CancellationToken ct = default) + { + var processMethod = GetType().GetMethod + ( + nameof(DispatchCommandHandler), + BindingFlags.NonPublic | BindingFlags.Instance + ); + + if (processMethod is null) + { + throw new InvalidOperationException("Could not find process command generic method in command processor."); + } + + var boundProcessMethod = processMethod.MakeGenericMethod(command.GetType()); + + return (Task)boundProcessMethod.Invoke(this, new object[] { command, ct })!; + } + + private Task DispatchCommandHandler(TCommand command, CancellationToken ct = default) + where TCommand : class, ICommand + { + using var scope = _provider.CreateScope(); + var commandHandler = scope.ServiceProvider.GetService>(); + if (commandHandler is null) + { + return Task.FromResult(Result.FromError(new CommandHandlerNotFound(command.GetType()))); + } + + return commandHandler.HandleCommand(command, ct); + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Commands/ICommand.cs b/Core/NosSmooth.Core/Commands/ICommand.cs index ebe26d9..bbbbb65 100644 --- a/Core/NosSmooth.Core/Commands/ICommand.cs +++ b/Core/NosSmooth.Core/Commands/ICommand.cs @@ -1,20 +1,20 @@ -// -// ICommand.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using NosSmooth.Core.Client; - -namespace NosSmooth.Core.Commands; - -/// -/// Represents command for . -/// -/// -/// Commands do complex operations that may take more time. -/// For handling commands, is used. -/// -public interface ICommand -{ +// +// ICommand.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using NosSmooth.Core.Client; + +namespace NosSmooth.Core.Commands; + +/// +/// Represents command for . +/// +/// +/// Commands do complex operations that may take more time. +/// For handling commands, is used. +/// +public interface ICommand +{ } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Commands/ICommandHandler.cs b/Core/NosSmooth.Core/Commands/ICommandHandler.cs index b18a7ed..6020b34 100644 --- a/Core/NosSmooth.Core/Commands/ICommandHandler.cs +++ b/Core/NosSmooth.Core/Commands/ICommandHandler.cs @@ -1,34 +1,34 @@ -// -// ICommandHandler.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading; -using System.Threading.Tasks; -using Remora.Results; - -namespace NosSmooth.Core.Commands; - -/// -/// Represents interface for command handlers that process . -/// -public interface ICommandHandler -{ -} - -/// -/// Represents interface of class that handles of type . -/// -/// The command type that this handler can execute. -public interface ICommandHandler : ICommandHandler - where TCommand : ICommand -{ - /// - /// Execute the given command. - /// - /// The command to execute. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task HandleCommand(TCommand command, CancellationToken ct = default); +// +// ICommandHandler.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading; +using System.Threading.Tasks; +using Remora.Results; + +namespace NosSmooth.Core.Commands; + +/// +/// Represents interface for command handlers that process . +/// +public interface ICommandHandler +{ +} + +/// +/// Represents interface of class that handles of type . +/// +/// The command type that this handler can execute. +public interface ICommandHandler : ICommandHandler + where TCommand : ICommand +{ + /// + /// Execute the given command. + /// + /// The command to execute. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task HandleCommand(TCommand command, CancellationToken ct = default); } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Commands/WalkCommand.cs b/Core/NosSmooth.Core/Commands/WalkCommand.cs index 3f0008f..7fa2499 100644 --- a/Core/NosSmooth.Core/Commands/WalkCommand.cs +++ b/Core/NosSmooth.Core/Commands/WalkCommand.cs @@ -1,16 +1,16 @@ -// -// WalkCommand.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace NosSmooth.Core.Commands; - -/// -/// Command that moves the player to the specified target position. -/// May be used only in world. -/// -/// The x coordinate of the target position to move to. -/// The y coordinate of the target position to move to. -/// Whether to cancel the walk when the user clicks to move somewhere. +// +// WalkCommand.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace NosSmooth.Core.Commands; + +/// +/// Command that moves the player to the specified target position. +/// May be used only in world. +/// +/// The x coordinate of the target position to move to. +/// The y coordinate of the target position to move to. +/// Whether to cancel the walk when the user clicks to move somewhere. public record WalkCommand(int TargetX, int TargetY, bool CancelOnUserMove = true) : ICommand; \ No newline at end of file diff --git a/Core/NosSmooth.Core/Errors/CommandHandlerNotFound.cs b/Core/NosSmooth.Core/Errors/CommandHandlerNotFound.cs index 6b70283..b5dd2d9 100644 --- a/Core/NosSmooth.Core/Errors/CommandHandlerNotFound.cs +++ b/Core/NosSmooth.Core/Errors/CommandHandlerNotFound.cs @@ -1,17 +1,17 @@ -// -// CommandHandlerNotFound.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using Remora.Results; - -namespace NosSmooth.Core.Errors; - -/// -/// Represents an error that tells the user there is no handler for the specified command so it cannot be processed. -/// -/// The type of the command. -public record CommandHandlerNotFound(Type CommandType) : ResultError( +// +// CommandHandlerNotFound.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using Remora.Results; + +namespace NosSmooth.Core.Errors; + +/// +/// Represents an error that tells the user there is no handler for the specified command so it cannot be processed. +/// +/// The type of the command. +public record CommandHandlerNotFound(Type CommandType) : ResultError( $"Could not process the command of type {CommandType.FullName}, because there is not a handler for it."); \ No newline at end of file diff --git a/Core/NosSmooth.Core/Extensions/ServiceCollectionExtensions.cs b/Core/NosSmooth.Core/Extensions/ServiceCollectionExtensions.cs index c95ef7f..6e26531 100644 --- a/Core/NosSmooth.Core/Extensions/ServiceCollectionExtensions.cs +++ b/Core/NosSmooth.Core/Extensions/ServiceCollectionExtensions.cs @@ -1,185 +1,185 @@ -// -// ServiceCollectionExtensions.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq; -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using NosCore.Packets; -using NosCore.Packets.Attributes; -using NosCore.Packets.Enumerations; -using NosCore.Packets.Interfaces; -using NosSmooth.Core.Client; -using NosSmooth.Core.Commands; -using NosSmooth.Core.Packets; -using NosSmooth.Core.Packets.Converters; - -namespace NosSmooth.Core.Extensions; - -/// -/// Contains extension methods for . -/// -public static class ServiceCollectionExtensions -{ - /// - /// Adds base packet and command handling for nostale client. - /// - /// The service collection to register the responder to. - /// Custom types of packets to serialize and deserialize. - /// The collection. - public static IServiceCollection AddNostaleCore - ( - this IServiceCollection serviceCollection, - params Type[] additionalPacketTypes - ) - { - serviceCollection - .TryAddSingleton(); - - var clientPacketTypes = typeof(IPacket).Assembly.GetTypes() - .Where(p => (p.Namespace?.Contains("Client") ?? false) && p.GetInterfaces().Contains(typeof(IPacket)) && p.IsClass && !p.IsAbstract).ToList(); - var serverPacketTypes = typeof(IPacket).Assembly.GetTypes() - .Where(p => (p.Namespace?.Contains("Server") ?? false) && p.GetInterfaces().Contains(typeof(IPacket)) && p.IsClass && !p.IsAbstract).ToList(); - - if (additionalPacketTypes.Length != 0) - { - clientPacketTypes.AddRange(additionalPacketTypes); - } - - serviceCollection.AddSingleton(p => - new PacketSerializerProvider(clientPacketTypes, serverPacketTypes, p)); - serviceCollection.AddSingleton(p => p.GetRequiredService().ServerSerializer); - - serviceCollection.AddSingleton(); - - serviceCollection.AddSpecificPacketConverter(); - - return serviceCollection; - } - - /// - /// Adds the specified packet responder that will be called upon receiving the given event. - /// - /// The service collection to register the responder to. - /// The type of the responder. - /// Thrown if the type of the responder is incorrect. - /// The collection. - public static IServiceCollection AddPacketResponder - ( - this IServiceCollection serviceCollection - ) - where TPacketResponder : class, IPacketResponder - { - return serviceCollection.AddPacketResponder(typeof(TPacketResponder)); - } - - /// - /// Adds the specified packet responder that will be called upon receiving the given event. - /// - /// The service collection to register the responder to. - /// The type of the responder. - /// The collection. - /// Thrown if the type of the responder is incorrect. - public static IServiceCollection AddPacketResponder - ( - this IServiceCollection serviceCollection, - Type responderType - ) - { - if (responderType.GetInterfaces().Any(i => i == typeof(IEveryPacketResponder))) - { - return serviceCollection.AddScoped(typeof(IEveryPacketResponder), responderType); - } - - if (!responderType.GetInterfaces().Any( - i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPacketResponder<>) - )) - { - throw new ArgumentException( - $"{nameof(responderType)} should implement IPacketResponder.", - nameof(responderType)); - } - - var responderTypeInterfaces = responderType.GetInterfaces(); - var responderInterfaces = responderTypeInterfaces.Where - ( - r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(IPacketResponder<>) - ); - - foreach (var responderInterface in responderInterfaces) - { - serviceCollection.AddScoped(responderInterface, responderType); - } - - return serviceCollection; - } - - /// - /// Adds the specified command handler. - /// - /// The service collection to register the responder to. - /// The type of the command. - /// Thrown if the type of the responder is incorrect. - /// The collection. - public static IServiceCollection AddCommandHandler - ( - this IServiceCollection serviceCollection - ) - where TCommandHandler : class, ICommandHandler - { - return serviceCollection.AddCommandHandler(typeof(TCommandHandler)); - } - - /// - /// Adds the specified command handler. - /// - /// The service collection to register the responder to. - /// The type of the command handler. - /// The collection. - /// Thrown if the type of the responder is incorrect. - public static IServiceCollection AddCommandHandler - ( - this IServiceCollection serviceCollection, - Type commandHandlerType - ) - { - if (!commandHandlerType.GetInterfaces().Any( - i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>) - )) - { - throw new ArgumentException( - $"{nameof(commandHandlerType)} should implement ICommandHandler.", - nameof(commandHandlerType)); - } - - var handlerTypeInterfaces = commandHandlerType.GetInterfaces(); - var handlerInterfaces = handlerTypeInterfaces.Where - ( - r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(ICommandHandler<>) - ); - - foreach (var handlerInterface in handlerInterfaces) - { - serviceCollection.AddScoped(handlerInterface, commandHandlerType); - } - - return serviceCollection; - } - - /// - /// Adds the specified packet converter. - /// - /// The service collection to register the responder to. - /// The type of the packet. - /// Thrown if the type of the responder is incorrect. - /// The collection. - public static IServiceCollection AddSpecificPacketConverter(this IServiceCollection serviceCollection) - where TPacketConverter : class, ISpecificPacketSerializer - { - return serviceCollection.AddSingleton(); - } +// +// ServiceCollectionExtensions.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Linq; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using NosCore.Packets; +using NosCore.Packets.Attributes; +using NosCore.Packets.Enumerations; +using NosCore.Packets.Interfaces; +using NosSmooth.Core.Client; +using NosSmooth.Core.Commands; +using NosSmooth.Core.Packets; +using NosSmooth.Core.Packets.Converters; + +namespace NosSmooth.Core.Extensions; + +/// +/// Contains extension methods for . +/// +public static class ServiceCollectionExtensions +{ + /// + /// Adds base packet and command handling for nostale client. + /// + /// The service collection to register the responder to. + /// Custom types of packets to serialize and deserialize. + /// The collection. + public static IServiceCollection AddNostaleCore + ( + this IServiceCollection serviceCollection, + params Type[] additionalPacketTypes + ) + { + serviceCollection + .TryAddSingleton(); + + var clientPacketTypes = typeof(IPacket).Assembly.GetTypes() + .Where(p => (p.Namespace?.Contains("Client") ?? false) && p.GetInterfaces().Contains(typeof(IPacket)) && p.IsClass && !p.IsAbstract).ToList(); + var serverPacketTypes = typeof(IPacket).Assembly.GetTypes() + .Where(p => (p.Namespace?.Contains("Server") ?? false) && p.GetInterfaces().Contains(typeof(IPacket)) && p.IsClass && !p.IsAbstract).ToList(); + + if (additionalPacketTypes.Length != 0) + { + clientPacketTypes.AddRange(additionalPacketTypes); + } + + serviceCollection.AddSingleton(p => + new PacketSerializerProvider(clientPacketTypes, serverPacketTypes, p)); + serviceCollection.AddSingleton(p => p.GetRequiredService().ServerSerializer); + + serviceCollection.AddSingleton(); + + serviceCollection.AddSpecificPacketConverter(); + + return serviceCollection; + } + + /// + /// Adds the specified packet responder that will be called upon receiving the given event. + /// + /// The service collection to register the responder to. + /// The type of the responder. + /// Thrown if the type of the responder is incorrect. + /// The collection. + public static IServiceCollection AddPacketResponder + ( + this IServiceCollection serviceCollection + ) + where TPacketResponder : class, IPacketResponder + { + return serviceCollection.AddPacketResponder(typeof(TPacketResponder)); + } + + /// + /// Adds the specified packet responder that will be called upon receiving the given event. + /// + /// The service collection to register the responder to. + /// The type of the responder. + /// The collection. + /// Thrown if the type of the responder is incorrect. + public static IServiceCollection AddPacketResponder + ( + this IServiceCollection serviceCollection, + Type responderType + ) + { + if (responderType.GetInterfaces().Any(i => i == typeof(IEveryPacketResponder))) + { + return serviceCollection.AddScoped(typeof(IEveryPacketResponder), responderType); + } + + if (!responderType.GetInterfaces().Any( + i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPacketResponder<>) + )) + { + throw new ArgumentException( + $"{nameof(responderType)} should implement IPacketResponder.", + nameof(responderType)); + } + + var responderTypeInterfaces = responderType.GetInterfaces(); + var responderInterfaces = responderTypeInterfaces.Where + ( + r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(IPacketResponder<>) + ); + + foreach (var responderInterface in responderInterfaces) + { + serviceCollection.AddScoped(responderInterface, responderType); + } + + return serviceCollection; + } + + /// + /// Adds the specified command handler. + /// + /// The service collection to register the responder to. + /// The type of the command. + /// Thrown if the type of the responder is incorrect. + /// The collection. + public static IServiceCollection AddCommandHandler + ( + this IServiceCollection serviceCollection + ) + where TCommandHandler : class, ICommandHandler + { + return serviceCollection.AddCommandHandler(typeof(TCommandHandler)); + } + + /// + /// Adds the specified command handler. + /// + /// The service collection to register the responder to. + /// The type of the command handler. + /// The collection. + /// Thrown if the type of the responder is incorrect. + public static IServiceCollection AddCommandHandler + ( + this IServiceCollection serviceCollection, + Type commandHandlerType + ) + { + if (!commandHandlerType.GetInterfaces().Any( + i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>) + )) + { + throw new ArgumentException( + $"{nameof(commandHandlerType)} should implement ICommandHandler.", + nameof(commandHandlerType)); + } + + var handlerTypeInterfaces = commandHandlerType.GetInterfaces(); + var handlerInterfaces = handlerTypeInterfaces.Where + ( + r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(ICommandHandler<>) + ); + + foreach (var handlerInterface in handlerInterfaces) + { + serviceCollection.AddScoped(handlerInterface, commandHandlerType); + } + + return serviceCollection; + } + + /// + /// Adds the specified packet converter. + /// + /// The service collection to register the responder to. + /// The type of the packet. + /// Thrown if the type of the responder is incorrect. + /// The collection. + public static IServiceCollection AddSpecificPacketConverter(this IServiceCollection serviceCollection) + where TPacketConverter : class, ISpecificPacketSerializer + { + return serviceCollection.AddSingleton(); + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/IsExternalInit.cs b/Core/NosSmooth.Core/IsExternalInit.cs index 7c63200..cba9385 100644 --- a/Core/NosSmooth.Core/IsExternalInit.cs +++ b/Core/NosSmooth.Core/IsExternalInit.cs @@ -1,15 +1,15 @@ -// -// IsExternalInit.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace System.Runtime.CompilerServices -{ - /// - /// Dummy. - /// - public class IsExternalInit - { - } +// +// IsExternalInit.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace System.Runtime.CompilerServices +{ + /// + /// Dummy. + /// + public class IsExternalInit + { + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/NosSmooth.Core.csproj b/Core/NosSmooth.Core/NosSmooth.Core.csproj index f79deb2..329d713 100644 --- a/Core/NosSmooth.Core/NosSmooth.Core.csproj +++ b/Core/NosSmooth.Core/NosSmooth.Core.csproj @@ -1,18 +1,18 @@ - - - - enable - 10 - net6.0;netstandard2.0 - - - - - - - - - - - - + + + + enable + 10 + net6.0;netstandard2.0 + + + + + + + + + + + + diff --git a/Core/NosSmooth.Core/Packets/Converters/ISpecificPacketSerializer.cs b/Core/NosSmooth.Core/Packets/Converters/ISpecificPacketSerializer.cs index e8bc893..b3bfb1e 100644 --- a/Core/NosSmooth.Core/Packets/Converters/ISpecificPacketSerializer.cs +++ b/Core/NosSmooth.Core/Packets/Converters/ISpecificPacketSerializer.cs @@ -1,132 +1,132 @@ -// -// ISpecificPacketSerializer.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Reflection; -using NosCore.Packets.Attributes; -using NosCore.Packets.Interfaces; -using Remora.Results; - -namespace NosSmooth.Core.Packets.Converters; - -/// -/// Converts packets that cannot be handled easily by the default serializer. -/// -public interface ISpecificPacketSerializer -{ - /// - /// Gets whether this is a serializer. - /// - public bool Serializer { get; } - - /// - /// Gets whether this is a deserializer. - /// - public bool Deserializer { get; } - - /// - /// Whether the current packet serializer should handle the packet. - /// - /// The string of the packet. - /// If this serializer should be used for handling. - public bool ShouldHandle(string packetString); - - /// - /// Whether the current packet serializer should handle the packet. - /// - /// The packet object. - /// If this serializer should be used for handling. - public bool ShouldHandle(IPacket packet); - - /// - /// Serialize the given packet into string. - /// - /// The string of the packet. - /// The serialized packet or an error. - public Result Serialize(IPacket packet); - - /// - /// Deserialize the given packet to its type. - /// - /// The string of the packet. - /// The deserialized packet or an error. - public Result Deserialize(string packetString); -} - -/// -/// Converts packets that cannot be handled easily by the default serializer. -/// -/// The packet. -public abstract class SpecificPacketSerializer : ISpecificPacketSerializer - where TPacket : IPacket -{ - private string? _packetHeader; - - /// - /// Gets the packet header identifier. - /// - public string PacketHeader - { - get - { - if (_packetHeader is null) - { - _packetHeader = typeof(TPacket).GetCustomAttribute()!.Identification + " "; - } - - return _packetHeader; - } - } - - /// - public abstract bool Serializer { get; } - - /// - public abstract bool Deserializer { get; } - - /// - public bool ShouldHandle(string packetString) - { - return packetString.StartsWith(PacketHeader); - } - - /// - public bool ShouldHandle(IPacket packet) - { - return typeof(TPacket) == packet.GetType(); - } - - /// - Result ISpecificPacketSerializer.Serialize(IPacket packet) - { - return Serialize((TPacket)packet); - } - - /// - Result ISpecificPacketSerializer.Deserialize(string packetString) - { - var result = Deserialize(packetString); - if (!result.IsSuccess) - { - return Result.FromError(result); - } - - return Result.FromSuccess(result.Entity); - } - - /// - /// Serialize the given packet into string. - /// - /// The string of the packet. - /// The serialized packet or an error. - public abstract Result Serialize(TPacket packet); - - /// - /// Deserialize the given packet to its type. - /// - /// The string of the packet. - /// The deserialized packet or an error. - public abstract Result Deserialize(string packetString); +// +// ISpecificPacketSerializer.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Reflection; +using NosCore.Packets.Attributes; +using NosCore.Packets.Interfaces; +using Remora.Results; + +namespace NosSmooth.Core.Packets.Converters; + +/// +/// Converts packets that cannot be handled easily by the default serializer. +/// +public interface ISpecificPacketSerializer +{ + /// + /// Gets whether this is a serializer. + /// + public bool Serializer { get; } + + /// + /// Gets whether this is a deserializer. + /// + public bool Deserializer { get; } + + /// + /// Whether the current packet serializer should handle the packet. + /// + /// The string of the packet. + /// If this serializer should be used for handling. + public bool ShouldHandle(string packetString); + + /// + /// Whether the current packet serializer should handle the packet. + /// + /// The packet object. + /// If this serializer should be used for handling. + public bool ShouldHandle(IPacket packet); + + /// + /// Serialize the given packet into string. + /// + /// The string of the packet. + /// The serialized packet or an error. + public Result Serialize(IPacket packet); + + /// + /// Deserialize the given packet to its type. + /// + /// The string of the packet. + /// The deserialized packet or an error. + public Result Deserialize(string packetString); +} + +/// +/// Converts packets that cannot be handled easily by the default serializer. +/// +/// The packet. +public abstract class SpecificPacketSerializer : ISpecificPacketSerializer + where TPacket : IPacket +{ + private string? _packetHeader; + + /// + /// Gets the packet header identifier. + /// + public string PacketHeader + { + get + { + if (_packetHeader is null) + { + _packetHeader = typeof(TPacket).GetCustomAttribute()!.Identification + " "; + } + + return _packetHeader; + } + } + + /// + public abstract bool Serializer { get; } + + /// + public abstract bool Deserializer { get; } + + /// + public bool ShouldHandle(string packetString) + { + return packetString.StartsWith(PacketHeader); + } + + /// + public bool ShouldHandle(IPacket packet) + { + return typeof(TPacket) == packet.GetType(); + } + + /// + Result ISpecificPacketSerializer.Serialize(IPacket packet) + { + return Serialize((TPacket)packet); + } + + /// + Result ISpecificPacketSerializer.Deserialize(string packetString) + { + var result = Deserialize(packetString); + if (!result.IsSuccess) + { + return Result.FromError(result); + } + + return Result.FromSuccess(result.Entity); + } + + /// + /// Serialize the given packet into string. + /// + /// The string of the packet. + /// The serialized packet or an error. + public abstract Result Serialize(TPacket packet); + + /// + /// Deserialize the given packet to its type. + /// + /// The string of the packet. + /// The deserialized packet or an error. + public abstract Result Deserialize(string packetString); } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/Converters/InPacketSerializer.cs b/Core/NosSmooth.Core/Packets/Converters/InPacketSerializer.cs index 07c8313..2d352cf 100644 --- a/Core/NosSmooth.Core/Packets/Converters/InPacketSerializer.cs +++ b/Core/NosSmooth.Core/Packets/Converters/InPacketSerializer.cs @@ -1,91 +1,91 @@ -// -// InPacketSerializer.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq; -using NosCore.Packets.ServerPackets.Visibility; -using NosCore.Shared.Enumerations; -using Remora.Results; - -namespace NosSmooth.Core.Packets.Converters; - -/// -/// Deserializes InPacket correctly. -/// -public class InPacketSerializer : SpecificPacketSerializer -{ - private readonly PacketSerializerProvider _packetSerializerProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The provider of packet serializer. - public InPacketSerializer(PacketSerializerProvider packetSerializerProvider) - { - _packetSerializerProvider = packetSerializerProvider; - } - - /// - public override bool Serializer => false; - - /// - public override bool Deserializer => true; - - /// - public override Result Serialize(InPacket packet) - { - throw new System.NotImplementedException(); - } - - /// - public override Result Deserialize(string packetString) - { - try - { - var deserializer = _packetSerializerProvider.ServerSerializer.Deserializer; - var splitted = packetString.Split(new char[] { ' ' }, 9).Skip(1).ToArray(); - - if (!Enum.TryParse(splitted[0], out VisualType type)) - { - return new ArgumentInvalidError(nameof(packetString), "The visual type is incorrect."); - } - - var startAddress = type == VisualType.Player ? 3 : 2; - var inPacket = new InPacket - { - VisualType = type, - VNum = type != VisualType.Player ? long.Parse(splitted[1]) : null, - Name = type == VisualType.Player ? splitted[1] : null, - VisualId = long.Parse(splitted[startAddress]), - PositionX = short.Parse(splitted[startAddress + 1]), - PositionY = short.Parse(splitted[startAddress + 2]), - Direction = byte.Parse(splitted[startAddress + 3]) - }; - - switch (inPacket.VisualType) - { - case VisualType.Player: - inPacket.InCharacterSubPacket = (InCharacterSubPacket?)deserializer - .DeserializeHeaderlessIPacket(typeof(InCharacterSubPacket), splitted[7]); - break; - case VisualType.Object: - inPacket.InItemSubPacket = (InItemSubPacket?)deserializer - .DeserializeHeaderlessIPacket(typeof(InItemSubPacket), splitted[6] + " " + splitted[7]); - break; - default: - inPacket.InNonPlayerSubPacket = (InNonPlayerSubPacket?)deserializer - .DeserializeHeaderlessIPacket(typeof(InNonPlayerSubPacket), splitted[6] + " " + splitted[7]); - break; - } - - return inPacket; - } - catch (Exception e) - { - return e; - } - } +// +// InPacketSerializer.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Linq; +using NosCore.Packets.ServerPackets.Visibility; +using NosCore.Shared.Enumerations; +using Remora.Results; + +namespace NosSmooth.Core.Packets.Converters; + +/// +/// Deserializes InPacket correctly. +/// +public class InPacketSerializer : SpecificPacketSerializer +{ + private readonly PacketSerializerProvider _packetSerializerProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The provider of packet serializer. + public InPacketSerializer(PacketSerializerProvider packetSerializerProvider) + { + _packetSerializerProvider = packetSerializerProvider; + } + + /// + public override bool Serializer => false; + + /// + public override bool Deserializer => true; + + /// + public override Result Serialize(InPacket packet) + { + throw new System.NotImplementedException(); + } + + /// + public override Result Deserialize(string packetString) + { + try + { + var deserializer = _packetSerializerProvider.ServerSerializer.Deserializer; + var splitted = packetString.Split(new char[] { ' ' }, 9).Skip(1).ToArray(); + + if (!Enum.TryParse(splitted[0], out VisualType type)) + { + return new ArgumentInvalidError(nameof(packetString), "The visual type is incorrect."); + } + + var startAddress = type == VisualType.Player ? 3 : 2; + var inPacket = new InPacket + { + VisualType = type, + VNum = type != VisualType.Player ? long.Parse(splitted[1]) : null, + Name = type == VisualType.Player ? splitted[1] : null, + VisualId = long.Parse(splitted[startAddress]), + PositionX = short.Parse(splitted[startAddress + 1]), + PositionY = short.Parse(splitted[startAddress + 2]), + Direction = byte.Parse(splitted[startAddress + 3]) + }; + + switch (inPacket.VisualType) + { + case VisualType.Player: + inPacket.InCharacterSubPacket = (InCharacterSubPacket?)deserializer + .DeserializeHeaderlessIPacket(typeof(InCharacterSubPacket), splitted[7]); + break; + case VisualType.Object: + inPacket.InItemSubPacket = (InItemSubPacket?)deserializer + .DeserializeHeaderlessIPacket(typeof(InItemSubPacket), splitted[6] + " " + splitted[7]); + break; + default: + inPacket.InNonPlayerSubPacket = (InNonPlayerSubPacket?)deserializer + .DeserializeHeaderlessIPacket(typeof(InNonPlayerSubPacket), splitted[6] + " " + splitted[7]); + break; + } + + return inPacket; + } + catch (Exception e) + { + return e; + } + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/IPacketHandler.cs b/Core/NosSmooth.Core/Packets/IPacketHandler.cs index ffef41b..e5ef885 100644 --- a/Core/NosSmooth.Core/Packets/IPacketHandler.cs +++ b/Core/NosSmooth.Core/Packets/IPacketHandler.cs @@ -1,36 +1,36 @@ -// -// IPacketHandler.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading; -using System.Threading.Tasks; -using NosCore.Packets.Interfaces; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -/// Calls registered responders for the packet that should be handled. -/// -public interface IPacketHandler -{ - /// - /// Calls a responder for the given packet. - /// - /// The packet. - /// The string of the packet. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task HandleReceivedPacketAsync(IPacket packet, string packetString, CancellationToken ct = default); - - /// - /// Calls a responder for the given packet. - /// - /// The packet. - /// The string of the packet. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task HandleSentPacketAsync(IPacket packet, string packetString, CancellationToken ct = default); +// +// IPacketHandler.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading; +using System.Threading.Tasks; +using NosCore.Packets.Interfaces; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +/// Calls registered responders for the packet that should be handled. +/// +public interface IPacketHandler +{ + /// + /// Calls a responder for the given packet. + /// + /// The packet. + /// The string of the packet. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task HandleReceivedPacketAsync(IPacket packet, string packetString, CancellationToken ct = default); + + /// + /// Calls a responder for the given packet. + /// + /// The packet. + /// The string of the packet. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task HandleSentPacketAsync(IPacket packet, string packetString, CancellationToken ct = default); } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/IPacketResponder.cs b/Core/NosSmooth.Core/Packets/IPacketResponder.cs index efda0f7..2c5f744 100644 --- a/Core/NosSmooth.Core/Packets/IPacketResponder.cs +++ b/Core/NosSmooth.Core/Packets/IPacketResponder.cs @@ -1,52 +1,52 @@ -// -// IPacketResponder.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading; -using System.Threading.Tasks; -using NosCore.Packets.Interfaces; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -/// Represents interface for classes that respond to packets. -/// -public interface IPacketResponder -{ -} - -/// -/// Represents interface for classes that respond to packets. -/// Responds to . -/// -/// The packet type this responder responds to. -public interface IPacketResponder : IPacketResponder - where TPacket : IPacket -{ - /// - /// Respond to the given packet. - /// - /// The packet to respond to. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task Respond(PacketEventArgs packet, CancellationToken ct = default); -} - -/// -/// Represents interface for classes that respond to every type of packets. -/// -public interface IEveryPacketResponder : IPacketResponder -{ - /// - /// Respond to the given packet. - /// - /// The packet to respond to. - /// The cancellation token for cancelling the operation. - /// The type of the packet. - /// A result that may or may not have succeeded. - public Task Respond(PacketEventArgs packet, CancellationToken ct = default) - where TPacket : IPacket; +// +// IPacketResponder.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Threading; +using System.Threading.Tasks; +using NosCore.Packets.Interfaces; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +/// Represents interface for classes that respond to packets. +/// +public interface IPacketResponder +{ +} + +/// +/// Represents interface for classes that respond to packets. +/// Responds to . +/// +/// The packet type this responder responds to. +public interface IPacketResponder : IPacketResponder + where TPacket : IPacket +{ + /// + /// Respond to the given packet. + /// + /// The packet to respond to. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task Respond(PacketEventArgs packet, CancellationToken ct = default); +} + +/// +/// Represents interface for classes that respond to every type of packets. +/// +public interface IEveryPacketResponder : IPacketResponder +{ + /// + /// Respond to the given packet. + /// + /// The packet to respond to. + /// The cancellation token for cancelling the operation. + /// The type of the packet. + /// A result that may or may not have succeeded. + public Task Respond(PacketEventArgs packet, CancellationToken ct = default) + where TPacket : IPacket; } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/IPacketSerializer.cs b/Core/NosSmooth.Core/Packets/IPacketSerializer.cs index 678f79a..9dc050e 100644 --- a/Core/NosSmooth.Core/Packets/IPacketSerializer.cs +++ b/Core/NosSmooth.Core/Packets/IPacketSerializer.cs @@ -1,44 +1,44 @@ -// -// IPacketSerializer.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using NosCore.Packets; -using NosCore.Packets.Interfaces; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -/// Represents serialiazer and deserializer of . -/// -public interface IPacketSerializer -{ - /// - /// Serializes the given into string. - /// - /// The packet to serialize. - /// The serialized packet. - public Result Serialize(IPacket packet); - - /// - /// Deserializes the given string into . - /// - /// The packet to deserialize. - /// The deserialized packet. - public Result Deserialize(string packetString); - - /// - /// Gets the inner serializer from NosCore. - /// - [Obsolete("May be removed anytime.")] - public Serializer Serializer { get; } - - /// - /// Gets the inner deserializer from NosCore. - /// - [Obsolete("May be removed anytime.")] - public Deserializer Deserializer { get; } +// +// IPacketSerializer.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using NosCore.Packets; +using NosCore.Packets.Interfaces; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +/// Represents serialiazer and deserializer of . +/// +public interface IPacketSerializer +{ + /// + /// Serializes the given into string. + /// + /// The packet to serialize. + /// The serialized packet. + public Result Serialize(IPacket packet); + + /// + /// Deserializes the given string into . + /// + /// The packet to deserialize. + /// The deserialized packet. + public Result Deserialize(string packetString); + + /// + /// Gets the inner serializer from NosCore. + /// + [Obsolete("May be removed anytime.")] + public Serializer Serializer { get; } + + /// + /// Gets the inner deserializer from NosCore. + /// + [Obsolete("May be removed anytime.")] + public Deserializer Deserializer { get; } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/PacketHandler.cs b/Core/NosSmooth.Core/Packets/PacketHandler.cs index 3a06978..775c9a8 100644 --- a/Core/NosSmooth.Core/Packets/PacketHandler.cs +++ b/Core/NosSmooth.Core/Packets/PacketHandler.cs @@ -1,104 +1,104 @@ -// -// PacketHandler.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using NosCore.Packets.Interfaces; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -public class PacketHandler : IPacketHandler -{ - private readonly IServiceProvider _provider; - - /// - /// Initializes a new instance of the class. - /// - /// The dependency injection provider. - public PacketHandler(IServiceProvider provider) - { - _provider = provider; - } - - /// - public Task HandleReceivedPacketAsync(IPacket packet, string packetString, CancellationToken ct) - => HandlePacketAsync(PacketType.Received, packet, packetString, ct); - - /// - public Task HandleSentPacketAsync(IPacket packet, string packetString, CancellationToken ct) - => HandlePacketAsync(PacketType.Sent, packet, packetString, ct); - - private Task HandlePacketAsync - ( - PacketType packetType, - IPacket packet, - string packetString, - CancellationToken ct = default - ) - { - var processMethod = GetType().GetMethod - ( - nameof(DispatchResponder), - BindingFlags.NonPublic | BindingFlags.Instance - ); - - if (processMethod is null) - { - throw new InvalidOperationException("Could not find process command generic method in command processor."); - } - - var boundProcessMethod = processMethod.MakeGenericMethod(packet.GetType()); - return (Task)boundProcessMethod.Invoke(this, new object[] - { - packetType, - packet, - packetString, - ct - })!; - } - - private async Task DispatchResponder( - PacketType packetType, - TPacket packet, - string packetString, - CancellationToken ct - ) - where TPacket : class, IPacket - { - using var scope = _provider.CreateScope(); - var packetResponders = scope.ServiceProvider.GetServices>(); - var genericPacketResponders = scope.ServiceProvider.GetServices(); - - var packetEventArgs = new PacketEventArgs(packetType, packet, packetString); - var tasks = packetResponders.Select(responder => responder.Respond(packetEventArgs, ct)).ToList(); - tasks.AddRange(genericPacketResponders.Select(responder => responder.Respond(packetEventArgs, ct))); - - var results = await Task.WhenAll(tasks); - - var errors = new List(); - foreach (var result in results) - { - if (!result.IsSuccess) - { - errors.Add(result); - } - } - - return errors.Count switch - { - 0 => Result.FromSuccess(), - 1 => errors[0], - _ => new AggregateError(errors.Cast().ToArray()) - }; - } +// +// PacketHandler.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using NosCore.Packets.Interfaces; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +public class PacketHandler : IPacketHandler +{ + private readonly IServiceProvider _provider; + + /// + /// Initializes a new instance of the class. + /// + /// The dependency injection provider. + public PacketHandler(IServiceProvider provider) + { + _provider = provider; + } + + /// + public Task HandleReceivedPacketAsync(IPacket packet, string packetString, CancellationToken ct) + => HandlePacketAsync(PacketType.Received, packet, packetString, ct); + + /// + public Task HandleSentPacketAsync(IPacket packet, string packetString, CancellationToken ct) + => HandlePacketAsync(PacketType.Sent, packet, packetString, ct); + + private Task HandlePacketAsync + ( + PacketType packetType, + IPacket packet, + string packetString, + CancellationToken ct = default + ) + { + var processMethod = GetType().GetMethod + ( + nameof(DispatchResponder), + BindingFlags.NonPublic | BindingFlags.Instance + ); + + if (processMethod is null) + { + throw new InvalidOperationException("Could not find process command generic method in command processor."); + } + + var boundProcessMethod = processMethod.MakeGenericMethod(packet.GetType()); + return (Task)boundProcessMethod.Invoke(this, new object[] + { + packetType, + packet, + packetString, + ct + })!; + } + + private async Task DispatchResponder( + PacketType packetType, + TPacket packet, + string packetString, + CancellationToken ct + ) + where TPacket : class, IPacket + { + using var scope = _provider.CreateScope(); + var packetResponders = scope.ServiceProvider.GetServices>(); + var genericPacketResponders = scope.ServiceProvider.GetServices(); + + var packetEventArgs = new PacketEventArgs(packetType, packet, packetString); + var tasks = packetResponders.Select(responder => responder.Respond(packetEventArgs, ct)).ToList(); + tasks.AddRange(genericPacketResponders.Select(responder => responder.Respond(packetEventArgs, ct))); + + var results = await Task.WhenAll(tasks); + + var errors = new List(); + foreach (var result in results) + { + if (!result.IsSuccess) + { + errors.Add(result); + } + } + + return errors.Count switch + { + 0 => Result.FromSuccess(), + 1 => errors[0], + _ => new AggregateError(errors.Cast().ToArray()) + }; + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/PacketSerializer.cs b/Core/NosSmooth.Core/Packets/PacketSerializer.cs index 0f6e3d0..3e2f0cb 100644 --- a/Core/NosSmooth.Core/Packets/PacketSerializer.cs +++ b/Core/NosSmooth.Core/Packets/PacketSerializer.cs @@ -1,88 +1,88 @@ -// -// PacketSerializer.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using NosCore.Packets; -using NosCore.Packets.Interfaces; -using NosSmooth.Core.Packets.Converters; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -public class PacketSerializer : IPacketSerializer -{ - private readonly Serializer _serializer; - private readonly Deserializer _deserializer; - private readonly IEnumerable _specificPacketSerializers; - - /// - /// Initializes a new instance of the class. - /// - /// The NosCore serializer. - /// The NosCore deserializer. - /// The specific packet serializers. - public PacketSerializer - ( - Serializer serializer, - Deserializer deserializer, - IEnumerable specificPacketSerializers - ) - { - _serializer = serializer; - _deserializer = deserializer; - _specificPacketSerializers = specificPacketSerializers; - } - - /// - public Result Serialize(IPacket packet) - { - try - { - foreach (var specificPacketSerializer in _specificPacketSerializers) - { - if (specificPacketSerializer.Serializer && specificPacketSerializer.ShouldHandle(packet)) - { - return specificPacketSerializer.Serialize(packet); - } - } - - return _serializer.Serialize(packet); - } - catch (Exception e) - { - return e; - } - } - - /// - public Result Deserialize(string packetString) - { - try - { - foreach (var specificPacketSerializer in _specificPacketSerializers) - { - if (specificPacketSerializer.Deserializer && specificPacketSerializer.ShouldHandle(packetString)) - { - return specificPacketSerializer.Deserialize(packetString); - } - } - - return Result.FromSuccess(_deserializer.Deserialize(packetString)); - } - catch (Exception e) - { - return e; - } - } - - /// - public Serializer Serializer => _serializer; - - /// - public Deserializer Deserializer => _deserializer; +// +// PacketSerializer.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using NosCore.Packets; +using NosCore.Packets.Interfaces; +using NosSmooth.Core.Packets.Converters; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +public class PacketSerializer : IPacketSerializer +{ + private readonly Serializer _serializer; + private readonly Deserializer _deserializer; + private readonly IEnumerable _specificPacketSerializers; + + /// + /// Initializes a new instance of the class. + /// + /// The NosCore serializer. + /// The NosCore deserializer. + /// The specific packet serializers. + public PacketSerializer + ( + Serializer serializer, + Deserializer deserializer, + IEnumerable specificPacketSerializers + ) + { + _serializer = serializer; + _deserializer = deserializer; + _specificPacketSerializers = specificPacketSerializers; + } + + /// + public Result Serialize(IPacket packet) + { + try + { + foreach (var specificPacketSerializer in _specificPacketSerializers) + { + if (specificPacketSerializer.Serializer && specificPacketSerializer.ShouldHandle(packet)) + { + return specificPacketSerializer.Serialize(packet); + } + } + + return _serializer.Serialize(packet); + } + catch (Exception e) + { + return e; + } + } + + /// + public Result Deserialize(string packetString) + { + try + { + foreach (var specificPacketSerializer in _specificPacketSerializers) + { + if (specificPacketSerializer.Deserializer && specificPacketSerializer.ShouldHandle(packetString)) + { + return specificPacketSerializer.Deserialize(packetString); + } + } + + return Result.FromSuccess(_deserializer.Deserialize(packetString)); + } + catch (Exception e) + { + return e; + } + } + + /// + public Serializer Serializer => _serializer; + + /// + public Deserializer Deserializer => _deserializer; } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/PacketSerializerProvider.cs b/Core/NosSmooth.Core/Packets/PacketSerializerProvider.cs index 2dac048..44d6645 100644 --- a/Core/NosSmooth.Core/Packets/PacketSerializerProvider.cs +++ b/Core/NosSmooth.Core/Packets/PacketSerializerProvider.cs @@ -1,83 +1,83 @@ -// -// PacketSerializerProvider.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using Microsoft.Extensions.DependencyInjection; -using NosCore.Packets; -using NosSmooth.Core.Packets.Converters; - -namespace NosSmooth.Core.Packets; - -/// -/// Provides serializer for the server or client packets. -/// -public class PacketSerializerProvider -{ - private readonly List _clientPacketTypes; - private readonly List _serverPacketTypes; - - private IPacketSerializer? _serverSerializer; - private IPacketSerializer? _clientSerializer; - private IServiceProvider _serviceProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The types of client packets. - /// The types of server packets. - /// The service provider for dependency injection. - public PacketSerializerProvider(List clientPacketTypes, List serverPacketTypes, IServiceProvider serviceProvider) - { - _clientPacketTypes = clientPacketTypes; - _serverPacketTypes = serverPacketTypes; - _serviceProvider = serviceProvider; - } - - /// - /// Gets the server serializer. - /// - public IPacketSerializer ServerSerializer - { - get - { - if (_serverSerializer is null) - { - _serverSerializer = - new PacketSerializer - ( - new Serializer(_serverPacketTypes), - new Deserializer(_serverPacketTypes), - _serviceProvider.GetServices() - ); - } - - return _serverSerializer; - } - } - - /// - /// Gets the client serializer. - /// - public IPacketSerializer ClientSerializer - { - get - { - if (_clientSerializer is null) - { - _clientSerializer = - new PacketSerializer - ( - new Serializer(_clientPacketTypes), - new Deserializer(_clientPacketTypes), - _serviceProvider.GetServices() - ); - } - - return _clientSerializer; - } - } +// +// PacketSerializerProvider.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection; +using NosCore.Packets; +using NosSmooth.Core.Packets.Converters; + +namespace NosSmooth.Core.Packets; + +/// +/// Provides serializer for the server or client packets. +/// +public class PacketSerializerProvider +{ + private readonly List _clientPacketTypes; + private readonly List _serverPacketTypes; + + private IPacketSerializer? _serverSerializer; + private IPacketSerializer? _clientSerializer; + private IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The types of client packets. + /// The types of server packets. + /// The service provider for dependency injection. + public PacketSerializerProvider(List clientPacketTypes, List serverPacketTypes, IServiceProvider serviceProvider) + { + _clientPacketTypes = clientPacketTypes; + _serverPacketTypes = serverPacketTypes; + _serviceProvider = serviceProvider; + } + + /// + /// Gets the server serializer. + /// + public IPacketSerializer ServerSerializer + { + get + { + if (_serverSerializer is null) + { + _serverSerializer = + new PacketSerializer + ( + new Serializer(_serverPacketTypes), + new Deserializer(_serverPacketTypes), + _serviceProvider.GetServices() + ); + } + + return _serverSerializer; + } + } + + /// + /// Gets the client serializer. + /// + public IPacketSerializer ClientSerializer + { + get + { + if (_clientSerializer is null) + { + _clientSerializer = + new PacketSerializer + ( + new Serializer(_clientPacketTypes), + new Deserializer(_clientPacketTypes), + _serviceProvider.GetServices() + ); + } + + return _clientSerializer; + } + } } \ No newline at end of file diff --git a/Core/NosSmooth.Core/Packets/ParsingFailedPacket.cs b/Core/NosSmooth.Core/Packets/ParsingFailedPacket.cs index eeaaa73..d7b9507 100644 --- a/Core/NosSmooth.Core/Packets/ParsingFailedPacket.cs +++ b/Core/NosSmooth.Core/Packets/ParsingFailedPacket.cs @@ -1,37 +1,37 @@ -// -// ParsingFailedPacket.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using NosCore.Packets; -using Remora.Results; - -namespace NosSmooth.Core.Packets; - -/// -/// Represents packet that failed to parse correctly. -/// -public class ParsingFailedPacket : PacketBase -{ - /// - /// Initializes a new instance of the class. - /// - /// The result from the serializer. - /// The full text of the packet. - public ParsingFailedPacket(IResult serializerResult, string packet) - { - SerializerResult = serializerResult; - Packet = packet; - } - - /// - /// Gets the result from the serializer. - /// - public IResult SerializerResult { get; } - - /// - /// Gets he full packet string. - /// - public string Packet { get; } +// +// ParsingFailedPacket.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using NosCore.Packets; +using Remora.Results; + +namespace NosSmooth.Core.Packets; + +/// +/// Represents packet that failed to parse correctly. +/// +public class ParsingFailedPacket : PacketBase +{ + /// + /// Initializes a new instance of the class. + /// + /// The result from the serializer. + /// The full text of the packet. + public ParsingFailedPacket(IResult serializerResult, string packet) + { + SerializerResult = serializerResult; + Packet = packet; + } + + /// + /// Gets the result from the serializer. + /// + public IResult SerializerResult { get; } + + /// + /// Gets he full packet string. + /// + public string Packet { get; } } \ No newline at end of file diff --git a/Core/NosSmooth.Extensions/Events/GMJoinedMap.cs b/Core/NosSmooth.Extensions/Events/GMJoinedMap.cs index 9c6c81a..4934a3c 100644 --- a/Core/NosSmooth.Extensions/Events/GMJoinedMap.cs +++ b/Core/NosSmooth.Extensions/Events/GMJoinedMap.cs @@ -1,7 +1,7 @@ -namespace NosSmooth.Extensions.Events -{ - public class GMJoinedMap - { - - } +namespace NosSmooth.Extensions.Events +{ + public class GMJoinedMap + { + + } } \ No newline at end of file diff --git a/Core/NosSmooth.Extensions/NosSmooth.Extensions.csproj b/Core/NosSmooth.Extensions/NosSmooth.Extensions.csproj index 84b8ca8..4b6d380 100644 --- a/Core/NosSmooth.Extensions/NosSmooth.Extensions.csproj +++ b/Core/NosSmooth.Extensions/NosSmooth.Extensions.csproj @@ -1,13 +1,13 @@ - - - - net6.0 - enable - enable - - - - - - - + + + + net6.0 + enable + enable + + + + + + + diff --git a/Core/NosSmooth.Game/Events/Handlers/EventDispatcher.cs b/Core/NosSmooth.Game/Events/Handlers/EventDispatcher.cs index 675fa74..ebc03b4 100644 --- a/Core/NosSmooth.Game/Events/Handlers/EventDispatcher.cs +++ b/Core/NosSmooth.Game/Events/Handlers/EventDispatcher.cs @@ -1,51 +1,51 @@ -// -// EventDispatcher.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using Microsoft.Extensions.DependencyInjection; -using Remora.Results; - -namespace NosSmooth.Game.Events.Handlers; - -/// -/// Dispatches with . -/// -public class EventDispatcher -{ - private readonly IServiceProvider _provider; - - /// - /// Initializes a new instance of the class. - /// - /// The services provider. - public EventDispatcher(IServiceProvider provider) - { - _provider = provider; - } - - /// - /// Dispatches game responders that are registered in the service collection. - /// - /// The event to dispatch. - /// The cancellation token for cancelling the operation. - /// The type of the event. - /// A result that may or may not have succeeded. - public async Task DispatchEvent(TEvent @event, CancellationToken ct = default) - where TEvent : IGameEvent - { - var results = await Task.WhenAll( - _provider - .GetServices>() - .Select(responder => responder.Respond(@event, ct)) - ); - - return results.Length switch - { - 0 => Result.FromSuccess(), - 1 => results[0], - _ => new AggregateError(results.Cast().ToArray()), - }; - } +// +// EventDispatcher.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.DependencyInjection; +using Remora.Results; + +namespace NosSmooth.Game.Events.Handlers; + +/// +/// Dispatches with . +/// +public class EventDispatcher +{ + private readonly IServiceProvider _provider; + + /// + /// Initializes a new instance of the class. + /// + /// The services provider. + public EventDispatcher(IServiceProvider provider) + { + _provider = provider; + } + + /// + /// Dispatches game responders that are registered in the service collection. + /// + /// The event to dispatch. + /// The cancellation token for cancelling the operation. + /// The type of the event. + /// A result that may or may not have succeeded. + public async Task DispatchEvent(TEvent @event, CancellationToken ct = default) + where TEvent : IGameEvent + { + var results = await Task.WhenAll( + _provider + .GetServices>() + .Select(responder => responder.Respond(@event, ct)) + ); + + return results.Length switch + { + 0 => Result.FromSuccess(), + 1 => results[0], + _ => new AggregateError(results.Cast().ToArray()), + }; + } } \ No newline at end of file diff --git a/Core/NosSmooth.Game/Events/Handlers/IGameResponder.cs b/Core/NosSmooth.Game/Events/Handlers/IGameResponder.cs index c5914e6..b649b82 100644 --- a/Core/NosSmooth.Game/Events/Handlers/IGameResponder.cs +++ b/Core/NosSmooth.Game/Events/Handlers/IGameResponder.cs @@ -1,34 +1,34 @@ -// -// IGameResponder.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using OneOf.Types; -using Remora.Results; - -namespace NosSmooth.Game.Events.Handlers; - -/// -/// Represents interface for classes that respond to . -/// -public interface IGameResponder -{ -} - -/// -/// Represents interface for classes that respond to game events. -/// Responds to . -/// -/// The event type this responder responds to. -public interface IGameResponder : IGameResponder - where TEvent : IGameEvent -{ - /// - /// Respond to the given packet. - /// - /// The packet to respond to. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public Task Respond(TEvent packet, CancellationToken ct = default); +// +// IGameResponder.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using OneOf.Types; +using Remora.Results; + +namespace NosSmooth.Game.Events.Handlers; + +/// +/// Represents interface for classes that respond to . +/// +public interface IGameResponder +{ +} + +/// +/// Represents interface for classes that respond to game events. +/// Responds to . +/// +/// The event type this responder responds to. +public interface IGameResponder : IGameResponder + where TEvent : IGameEvent +{ + /// + /// Respond to the given packet. + /// + /// The packet to respond to. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public Task Respond(TEvent packet, CancellationToken ct = default); } \ No newline at end of file diff --git a/Core/NosSmooth.Game/Extensions/ServiceCollectionExtensions.cs b/Core/NosSmooth.Game/Extensions/ServiceCollectionExtensions.cs index d2f738e..e2466c7 100644 --- a/Core/NosSmooth.Game/Extensions/ServiceCollectionExtensions.cs +++ b/Core/NosSmooth.Game/Extensions/ServiceCollectionExtensions.cs @@ -1,44 +1,44 @@ - - /// - /// Adds the given game event responder. - /// - /// The service collection. - /// The responder to add. - /// The collection. - public static IServiceCollection AddGameResponder(this IServiceCollection serviceCollection) - where TGameResponder : IGameResponder - { - return serviceCollection.AddGameResponder(typeof(TGameResponder)); - } - - /// - /// Adds the given game event responder. - /// - /// The service collection. - /// The type of the event responder. - /// The collection. - public static IServiceCollection AddGameResponder(this IServiceCollection serviceCollection, Type gameResponder) - { - if (!gameResponder.GetInterfaces().Any( - i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGameResponder<>) - )) - { - throw new ArgumentException( - $"{nameof(gameResponder)} should implement IGameResponder.", - nameof(gameResponder)); - } - - var handlerTypeInterfaces = gameResponder.GetInterfaces(); - var handlerInterfaces = handlerTypeInterfaces.Where - ( - r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(IGameResponder<>) - ); - - foreach (var handlerInterface in handlerInterfaces) - { - serviceCollection.AddScoped(handlerInterface, gameResponder); - } - - return serviceCollection; - } + + /// + /// Adds the given game event responder. + /// + /// The service collection. + /// The responder to add. + /// The collection. + public static IServiceCollection AddGameResponder(this IServiceCollection serviceCollection) + where TGameResponder : IGameResponder + { + return serviceCollection.AddGameResponder(typeof(TGameResponder)); + } + + /// + /// Adds the given game event responder. + /// + /// The service collection. + /// The type of the event responder. + /// The collection. + public static IServiceCollection AddGameResponder(this IServiceCollection serviceCollection, Type gameResponder) + { + if (!gameResponder.GetInterfaces().Any( + i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGameResponder<>) + )) + { + throw new ArgumentException( + $"{nameof(gameResponder)} should implement IGameResponder.", + nameof(gameResponder)); + } + + var handlerTypeInterfaces = gameResponder.GetInterfaces(); + var handlerInterfaces = handlerTypeInterfaces.Where + ( + r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(IGameResponder<>) + ); + + foreach (var handlerInterface in handlerInterfaces) + { + serviceCollection.AddScoped(handlerInterface, gameResponder); + } + + return serviceCollection; + } } \ No newline at end of file diff --git a/Core/NosSmooth.Game/NosSmooth.Game.csproj b/Core/NosSmooth.Game/NosSmooth.Game.csproj index 76b9f93..5d7e9f0 100644 --- a/Core/NosSmooth.Game/NosSmooth.Game.csproj +++ b/Core/NosSmooth.Game/NosSmooth.Game.csproj @@ -1,10 +1,10 @@ - - - - enable - enable - 10 - net6.0;netstandard2.0 - - - + + + + enable + enable + 10 + net6.0;netstandard2.0 + + + diff --git a/Core/NosSmooth.Language/NosSmooth.Language.csproj b/Core/NosSmooth.Language/NosSmooth.Language.csproj index 76b9f93..5d7e9f0 100644 --- a/Core/NosSmooth.Language/NosSmooth.Language.csproj +++ b/Core/NosSmooth.Language/NosSmooth.Language.csproj @@ -1,10 +1,10 @@ - - - - enable - enable - 10 - net6.0;netstandard2.0 - - - + + + + enable + enable + 10 + net6.0;netstandard2.0 + + + diff --git a/DllExport.bat b/DllExport.bat index c62293f..8c4603a 100644 --- a/DllExport.bat +++ b/DllExport.bat @@ -1,509 +1,509 @@ -@echo off -:: Copyright (c) 2016-2021 Denis Kuzmin [x-3F@outlook.com] github/3F -:: https://github.com/3F/DllExport -if "%~1"=="/?" goto bq -set "aa=%~dpnx0" -set ab=%* -set ac=%* -if defined ab ( -if defined __p_call ( -set ac=%ac:^^=^% -) else ( -set ab=%ab:^=^^% -) -) -set wMgrArgs=%ac% -set ad=%ab:!=^!% -setlocal enableDelayedExpansion -set "ae=^" -set "ad=!ad:%%=%%%%!" -set "ad=!ad:&=%%ae%%&!" -set "af=1.7.4" -set "wAction=Configure" -set "ag=DllExport" -set "ah=tools/net.r_eg.DllExport.Wizard.targets" -set "ai=packages" -set "aj=https://www.nuget.org/api/v2/package/" -set "ak=build_info.txt" -set "al=!aa!" -set "wRootPath=!cd!" -set /a wDxpOpt=0 -set "am=" -set "an=" -set "ao=" -set "ap=" -set "aq=" -set "ar=" -set "as=" -set "at=" -set "au=" -set "av=" -set /a aw=0 -if not defined ab ( -if defined wAction goto br -goto bq -) -call :bs bk !ad! bl -goto bt -:bq -echo. -@echo .NET DllExport v1.7.4.29858+c1cc52f -@echo Copyright (c) 2009-2015 Robert Giesecke -@echo Copyright (c) 2016-2021 Denis Kuzmin ^ github/3F -echo. -echo MIT License -@echo https://github.com/3F/DllExport -echo Based on hMSBuild, MvsSln, +GetNuTool: https://github.com/3F -echo. -@echo. -@echo Usage: DllExport [args to DllExport] [args to GetNuTool] [args to hMSBuild] -echo ------ -echo. -echo Arguments -echo --------- -echo -action {type} - Specified action for Wizard. Where {type}: -echo * Configure - To configure DllExport for specific projects. -echo * Update - To update pkg reference for already configured projects. -echo * Restore - To restore configured DllExport. -echo * Export - To export configured projects data. -echo * Recover - To re-configure projects via predefined/exported data. -echo * Unset - To unset all data from specified projects. -echo * Upgrade - Aggregates an Update action with additions for upgrading. -echo. -echo -sln-dir {path} - Path to directory with .sln files to be processed. -echo -sln-file {path} - Optional predefined .sln file to be processed. -echo -metalib {path} - Relative path to meta library. -echo -metacor {path} - Relative path to meta core library. -echo -dxp-target {path} - Relative path to entrypoint wrapper of the main core. -echo -dxp-version {num} - Specific version of DllExport. Where {num}: -echo * Versions: 1.7.3 ... -echo * Keywords: -echo `actual` - Unspecified local/latest remote version; -echo ( Only if you know what you are doing ) -echo. -echo -msb {path} - Full path to specific msbuild. -echo -hMSBuild {args} - Access to hMSBuild tool (packed) https://github.com/3F/hMSBuild -echo -packages {path} - A common directory for packages. -echo -server {url} - Url for searching remote packages. -echo -proxy {cfg} - To use proxy. The format: [usr[:pwd]@]host[:port] -echo -pkg-link {uri} - Direct link to package from the source via specified URI. -echo -force - Aggressive behavior, e.g. like removing pkg when updating. -echo -no-mgr - Do not use %~nx0 for automatic restore the remote package. -echo -mgr-up - Updates %~nx0 to version from '-dxp-version'. -echo -wz-target {path} - Relative path to entrypoint wrapper of the main wizard. -echo -pe-exp-list {module} - To list all available exports from PE32/PE32+ module. -echo -eng - Try to use english language for all build messages. -echo -GetNuTool {args} - Access to GetNuTool (integrated) https://github.com/3F/GetNuTool -echo -debug - To show additional information. -echo -version - Displays version for which (together with) it was compiled. -echo -build-info - Displays actual build information from selected DllExport. -echo -help - Displays this help. Aliases: -help -h -echo. -echo Flags -echo ----- -echo __p_call - To use the call-type logic when invoking %~nx0 -echo. -echo Samples -echo ------- -echo DllExport -action Configure -force -pkg-link http://host/v1.7.3.nupkg -echo DllExport -action Restore -sln-file "Conari.sln" -echo DllExport -proxy guest:1234@10.0.2.15:7428 -action Configure -echo. -echo DllExport -mgr-up -dxp-version 1.7.3 -echo DllExport -action Upgrade -dxp-version 1.7.3 -echo. -echo DllExport -GetNuTool /p:ngpackages="Conari;regXwild" -echo DllExport -pe-exp-list bin\Debug\regXwild.dll -goto bu -:bt -set /a ax=0 -:bv -set ay=!bk[%ax%]! -if [!ay!]==[-help] ( goto bq ) else if [!ay!]==[-h] ( goto bq ) else if [!ay!]==[-?] ( goto bq ) -if [!ay!]==[-debug] ( -set am=1 -goto bw -) else if [!ay!]==[-action] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wAction=!v! -for %%g in (Restore, Configure, Update, Export, Recover, Unset, Upgrade, Default) do ( -if "!v!"=="%%g" goto bw -) -echo Unknown -action !v! -exit/B 1 -) else if [!ay!]==[-sln-dir] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wSlnDir=!v! -goto bw -) else if [!ay!]==[-sln-file] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wSlnFile=!v! -goto bw -) else if [!ay!]==[-metalib] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wMetaLib=!v! -goto bw -) else if [!ay!]==[-metacor] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wMetaCor=!v! -goto bw -) else if [!ay!]==[-dxp-target] ( set /a "ax+=1" & call :bx bk[!ax!] v -set wDxpTarget=!v! -goto bw -) else if [!ay!]==[-dxp-version] ( set /a "ax+=1" & call :bx bk[!ax!] v -set af=!v! -goto bw -) else if [!ay!]==[-msb] ( set /a "ax+=1" & call :bx bk[!ax!] v -set ao=!v! -goto bw -) else if [!ay!]==[-packages] ( set /a "ax+=1" & call :bx bk[!ax!] v -set ai=!v! -goto bw -) else if [!ay!]==[-server] ( set /a "ax+=1" & call :bx bk[!ax!] v -set aj=!v! -goto bw -) else if [!ay!]==[-proxy] ( set /a "ax+=1" & call :bx bk[!ax!] v -set at=!v! -set wProxy=!v! -goto bw -) else if [!ay!]==[-pkg-link] ( set /a "ax+=1" & call :bx bk[!ax!] v -set ap=!v! -set af=!ay! -goto bw -) else if [!ay!]==[-force] ( -set ar=1 -goto bw -) else if [!ay!]==[-no-mgr] ( -set /a wDxpOpt^|=1 -goto bw -) else if [!ay!]==[-mgr-up] ( -set as=1 -goto bw -) else if [!ay!]==[-wz-target] ( set /a "ax+=1" & call :bx bk[!ax!] v -set ah=!v! -goto bw -) else if [!ay!]==[-pe-exp-list] ( set /a "ax+=1" & call :bx bk[!ax!] v -set aq=!v! -goto bw -) else if [!ay!]==[-eng] ( -chcp 437 >nul -goto bw -) else if [!ay!]==[-GetNuTool] ( -call :by -GetNuTool 10 -set /a aw=!ERRORLEVEL! & goto bu -) else if [!ay!]==[-hMSBuild] ( -set av=1 & goto br -) else if [!ay!]==[-version] ( -@echo v1.7.4.29858+c1cc52f %__dxp_pv% -goto bu -) else if [!ay!]==[-build-info] ( -set an=1 -goto bw -) else if [!ay!]==[-tests] ( set /a "ax+=1" & call :bx bk[!ax!] v -set au=!v! -goto bw -) else ( -echo Incorrect key: !ay! -set /a aw=1 -goto bu -) -:bw -set /a "ax+=1" & if %ax% LSS !bl! goto bv -:br -call :bz "dxpName = " ag -call :bz "dxpVersion = " af -call :bz "-sln-dir = " wSlnDir -call :bz "-sln-file = " wSlnFile -call :bz "-metalib = " wMetaLib -call :bz "-metacor = " wMetaCor -call :bz "-dxp-target = " wDxpTarget -call :bz "-wz-target = " ah -call :bz "#opt " wDxpOpt -if defined af ( -if "!af!"=="actual" ( -set "af=" -) -) -set wPkgVer=!af! -if z%wAction%==zUpgrade ( -call :bz "Upgrade is on" -set as=1 -set ar=1 -) -call :b0 ai -set "ai=!ai!\\" -set "az=!ag!" -set "wPkgPath=!ai!!ag!" -if defined af ( -set "az=!az!/!af!" -set "wPkgPath=!wPkgPath!.!af!" -) -if defined ar ( -if exist "!wPkgPath!" ( -call :bz "Removing old version before continue. '-force' key rule. " wPkgPath -rmdir /S/Q "!wPkgPath!" -) -) -set a0="!wPkgPath!\\!ah!" -call :bz "wPkgPath = " wPkgPath -if not exist !a0! ( -if exist "!wPkgPath!" ( -call :bz "Trying to replace obsolete version ... " wPkgPath -rmdir /S/Q "!wPkgPath!" -) -call :bz "-pkg-link = " ap -call :bz "-server = " aj -if defined ap ( -set aj=!ap! -if "!aj::=!"=="!aj!" ( -set aj=!cd!/!aj! -) -if "!wPkgPath::=!"=="!wPkgPath!" ( -set "a1=../" -) -set "az=:!a1!!wPkgPath!|" -) -if defined ao ( -set a2=-msbuild "!ao!" -) -set a3=!a2! /p:ngserver="!aj!" /p:ngpackages="!az!" /p:ngpath="!ai!" /p:proxycfg="!at! " -call :bz "GetNuTool call: " a3 -if defined am ( -call :b1 !a3! -) else ( -call :b1 !a3! >nul -) -) -if defined av ( -call :by -hMSBuild 9 -set /a aw=!ERRORLEVEL! & goto bu -) -if defined aq ( -"!wPkgPath!\\tools\\PeViewer.exe" -list -pemodule "!aq!" -set /a aw=%ERRORLEVEL% -goto bu -) -if defined an ( -call :bz "buildInfo = " wPkgPath ak -if not exist "!wPkgPath!\\!ak!" ( -echo information about build is not available. -set /a aw=2 -goto bu -) -type "!wPkgPath!\\!ak!" -goto bu -) -if not exist !a0! ( -echo Something went wrong. Try to use another keys. -set /a aw=2 -goto bu -) -call :bz "wRootPath = " wRootPath -call :bz "wAction = " wAction -call :bz "wMgrArgs = " wMgrArgs -if defined ao ( -call :bz "Use specific MSBuild tools: " ao -set a4="!ao!" -goto b2 -) -call :b3 bm & set a4="!bm!" -if "!ERRORLEVEL!"=="0" goto b2 -echo MSBuild tools was not found. Try with `-msb` key. -set /a aw=2 -goto bu -:b2 -if not defined a4 ( -echo Something went wrong. Use `-debug` key for details. -set /a aw=2 -goto bu -) -if not defined au ( -if not defined ao if defined wPkgPath ( -set a4="!wPkgPath!\\hMSBuild" -for /f "tokens=*" %%i in ('!a4! -version') do set a5=%%i -call :b4 !a5! bn -call :bz "hMSBuild -v" a5 bn -if !bn! GEQ 230 ( -call :bz "2.3+" -set a4=!a4! -vsw-as "-requiresAny -requires Microsoft.NetCore.Component.SDK Microsoft.Net.Core.Component.SDK -products * -latest -prerelease" -) -) -call :bz "Target: " a4 a0 -call !a4! /nologo /v:m /m:4 !a0! -) -:bu -if defined au ( -echo Running Tests ... "!au!" -call :b3 bo -"!bo!" /nologo /v:m /m:4 "!au!" -exit/B 0 -) -if defined as ( -(copy /B/Y "!wPkgPath!\\DllExport.bat" "!al!" > nul) && ( echo Manager has been updated. & exit/B 0 ) || ( (echo -mgr-up failed:!aw! 1>&2) & exit/B 1 ) -) -exit/B !aw! -:b4 -set a6=%~1 -for /f "tokens=1,2 delims=." %%a in ("!a6!") do ( -set _=%%b & set /a _*=10 & set /a %2=%%a!_! -) -exit/B 0 -:by -set ay=%~1 -set /a a7=%~2 -call :bz "accessing to !ay! ..." -for /L %%p IN (0,1,8181) DO ( -if "!ad:~%%p,%a7%!"=="!ay!" ( -set a8=!ad:~%%p! -set a9=!a8:~%a7%! -if defined av ( -call "!wPkgPath!\\hMSBuild" !a9! -) else ( -call :b1 !a9! -) -exit/B !ERRORLEVEL! -) -) -call :bz "!ay! is corrupted: " ad -exit/B 1 -:b3 -call :bz "Searching from .NET Framework - .NET 4.0, ..." -for %%v in (4.0, 3.5, 2.0) do ( -call :b5 %%v Y & if defined Y ( -set %1=!Y! -exit/B 0 -) -) -call :bz "msb -netfx: not found" -set "%1=" -exit/B 2 -:b5 -call :bz "check %1" -for /F "usebackq tokens=2* skip=2" %%a in ( -`reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\%1" /v MSBuildToolsPath 2^> nul` -) do if exist %%b ( -set a_=%%~b -call :bz ":msbfound " a_ -call :b6 a_ bp -set %2=!bp! -exit/B 0 -) -set "%2=" -exit/B 0 -:b6 -set %2=!%~1!\MSBuild.exe -exit/B 0 -:bz -if defined am ( -set ba=%1 -set ba=!ba:~0,-1! -set ba=!ba:~1! -echo.[%TIME% ] !ba! !%2! !%3! -) -exit/B 0 -:b0 -call :b7 %1 -call :b8 %1 -exit/B 0 -:b7 -call :b9 %1 "-=1" -exit/B 0 -:b8 -call :b9 %1 "+=1" -exit/B 0 -:b9 -set bb=z!%1!z -if "%~2"=="-=1" (set "bc=1") else (set "bc=") -if defined bc ( -set /a "i=-2" -) else ( -set /a "i=1" -) -:b_ -if "!bb:~%i%,1!"==" " ( -set /a "i%~2" -goto b_ -) -if defined bc set /a "i+=1" -if defined bc ( -set "%1=!bb:~1,%i%!" -) else ( -set "%1=!bb:~%i%,-1!" -) -exit/B 0 -:bs -set "bd=%~1" -set /a ax=-1 -:ca -set /a ax+=1 -set %bd%[!ax!]=%~2 -shift & if not "%~3"=="" goto ca -set /a ax-=1 -set %1=!ax! -exit/B 0 -:bx -set %2=!%1! -exit/B 0 -:b1 -setlocal disableDelayedExpansion -@echo off -:: GetNuTool - Executable version -:: Copyright (c) 2015-2018,2020 Denis Kuzmin [ x-3F@outlook.com ] -:: https://github.com/3F/GetNuTool -set be=gnt.core -set bf="%temp%\%random%%random%%be%" -if "%~1"=="-unpack" goto cb -set bg=%* -if defined __p_call if defined bg set bg=%bg:^^=^% -set bh=%__p_msb% -if defined bh goto cc -if "%~1"=="-msbuild" goto cd -for %%v in (4.0, 14.0, 12.0, 3.5, 2.0) do ( -for /F "usebackq tokens=2* skip=2" %%a in ( -`reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\%%v" /v MSBuildToolsPath 2^> nul` -) do if exist %%b ( -set bh="%%~b\MSBuild.exe" -goto cc -) -) -echo MSBuild was not found. Try -msbuild "fullpath" args 1>&2 -exit/B 2 -:cd -shift -set bh=%1 -shift -set bi=%bg:!= #__b_ECL## % -setlocal enableDelayedExpansion -set bi=!bi:%%=%%%%! -:ce -for /F "tokens=1* delims==" %%a in ("!bi!") do ( -if "%%~b"=="" ( -call :cf !bi! -exit/B %ERRORLEVEL% -) -set bi=%%a #__b_EQ## %%b -) -goto ce -:cf -shift & shift -set "bg=" -:cg -set bg=!bg! %1 -shift & if not "%~2"=="" goto cg -set bg=!bg: #__b_EQ## ==! -setlocal disableDelayedExpansion -set bg=%bg: #__b_ECL## =!% -:cc -call :ch -call %bh% %bf% /nologo /p:wpath="%cd%/" /v:m /m:4 %bg% -set "bh=" -set bj=%ERRORLEVEL% -del /Q/F %bf% -exit/B %bj% -:cb -set bf="%cd%\%be%" -echo Generating minified version in %bf% ... -:ch -%bf% -set a=PropertyGroup&set b=Condition&set c=ngpackages&set d=Target&set e=DependsOnTargets&set f=TaskCoreDllPath&set g=MSBuildToolsPath&set h=UsingTask&set i=CodeTaskFactory&set j=ParameterGroup&set k=Reference&set l=Include&set m=System&set n=Using&set o=Namespace&set p=IsNullOrEmpty&set q=return&set r=string&set s=delegate&set t=foreach&set u=WriteLine&set v=Combine&set w=Console.WriteLine&set x=Directory&set y=GetNuTool&set z=StringComparison&set _=EXT_NUSPEC -^ - - + + + + + Debug + AnyCPU + {2A3EA9A8-5948-47FD-AD13-6E19540BDDFB} + Library + Properties + NosSmooth.RemoteClient + NosSmooth.RemoteClient + v4.7.2 + 512 + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + diff --git a/Remote/NosSmooth.RemoteClient/Properties/AssemblyInfo.cs b/Remote/NosSmooth.RemoteClient/Properties/AssemblyInfo.cs index f019b39..ceb9143 100644 --- a/Remote/NosSmooth.RemoteClient/Properties/AssemblyInfo.cs +++ b/Remote/NosSmooth.RemoteClient/Properties/AssemblyInfo.cs @@ -1,35 +1,35 @@ -using System.Reflection; -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("NosSmooth.RemoteClient")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NosSmooth.RemoteClient")] -[assembly: AssemblyCopyright("Copyright © 2021")] -[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("2A3EA9A8-5948-47FD-AD13-6E19540BDDFB")] - -// 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")] +using System.Reflection; +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("NosSmooth.RemoteClient")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("NosSmooth.RemoteClient")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[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("2A3EA9A8-5948-47FD-AD13-6E19540BDDFB")] + +// 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")] \ No newline at end of file diff --git a/Samples/DamageCounter/App.xaml b/Samples/DamageCounter/App.xaml index 3f594c2..a14f70b 100644 --- a/Samples/DamageCounter/App.xaml +++ b/Samples/DamageCounter/App.xaml @@ -1,9 +1,9 @@ - - - - - + + + + + diff --git a/Samples/DamageCounter/App.xaml.cs b/Samples/DamageCounter/App.xaml.cs index 71d160d..d350bb4 100644 --- a/Samples/DamageCounter/App.xaml.cs +++ b/Samples/DamageCounter/App.xaml.cs @@ -1,17 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; - -namespace DamageCounter -{ - /// - /// Interaction logic for App.xaml - /// - public partial class App : Application - { - } +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace DamageCounter +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } } \ No newline at end of file diff --git a/Samples/DamageCounter/AssemblyInfo.cs b/Samples/DamageCounter/AssemblyInfo.cs index 4a05c7d..5d08a02 100644 --- a/Samples/DamageCounter/AssemblyInfo.cs +++ b/Samples/DamageCounter/AssemblyInfo.cs @@ -1,10 +1,10 @@ -using System.Windows; - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) )] \ No newline at end of file diff --git a/Samples/DamageCounter/DamageCounter.csproj b/Samples/DamageCounter/DamageCounter.csproj index 86b3c42..20764b7 100644 --- a/Samples/DamageCounter/DamageCounter.csproj +++ b/Samples/DamageCounter/DamageCounter.csproj @@ -1,10 +1,10 @@ - - - - WinExe - net5.0-windows - enable - true - - - + + + + WinExe + net5.0-windows + enable + true + + + diff --git a/Samples/DamageCounter/MainWindow.xaml b/Samples/DamageCounter/MainWindow.xaml index fd01a93..869aaa7 100644 --- a/Samples/DamageCounter/MainWindow.xaml +++ b/Samples/DamageCounter/MainWindow.xaml @@ -1,12 +1,12 @@ - - - - - + + + + + diff --git a/Samples/DamageCounter/MainWindow.xaml.cs b/Samples/DamageCounter/MainWindow.xaml.cs index a698104..3455151 100644 --- a/Samples/DamageCounter/MainWindow.xaml.cs +++ b/Samples/DamageCounter/MainWindow.xaml.cs @@ -1,28 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -namespace DamageCounter -{ - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow : Window - { - public MainWindow() - { - InitializeComponent(); - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace DamageCounter +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + } + } } \ No newline at end of file diff --git a/Samples/InterceptNameChanger/DllMain.cs b/Samples/InterceptNameChanger/DllMain.cs index c01e6e1..e8b2bd9 100644 --- a/Samples/InterceptNameChanger/DllMain.cs +++ b/Samples/InterceptNameChanger/DllMain.cs @@ -32,13 +32,13 @@ namespace InterceptNameChanger new Thread(() => { - try - { - new NameChanger().RunAsync().GetAwaiter().GetResult(); + try + { + new NameChanger().RunAsync().GetAwaiter().GetResult(); } - catch (Exception e) - { - Console.WriteLine(e.ToString()); + catch (Exception e) + { + Console.WriteLine(e.ToString()); } }).Start(); } diff --git a/Samples/InterceptNameChanger/FodyWeavers.xml b/Samples/InterceptNameChanger/FodyWeavers.xml index 5029e70..f1dea8f 100644 --- a/Samples/InterceptNameChanger/FodyWeavers.xml +++ b/Samples/InterceptNameChanger/FodyWeavers.xml @@ -1,3 +1,3 @@ - - + + \ No newline at end of file diff --git a/Samples/InterceptNameChanger/InterceptNameChanger.csproj b/Samples/InterceptNameChanger/InterceptNameChanger.csproj index 6a226ab..19e91bf 100644 --- a/Samples/InterceptNameChanger/InterceptNameChanger.csproj +++ b/Samples/InterceptNameChanger/InterceptNameChanger.csproj @@ -1,67 +1,67 @@ - - - net48 - enable - enable - 10 - - - 89E4EE92-5848-4390-A6A7-34972FE923F5 - DllExport.dll - InterceptNameChanger - true - x86 - 7 - false - false - false - false - 30000 - 2 - 0 - 0 - 0 - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - 1.7.4 - false - 1 - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) - False - False - - - - - - + + + net48 + enable + enable + 10 + + + 89E4EE92-5848-4390-A6A7-34972FE923F5 + DllExport.dll + InterceptNameChanger + true + x86 + 7 + false + false + false + false + 30000 + 2 + 0 + 0 + 0 + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + 1.7.4 + false + 1 + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) + False + False + + + + + + \ No newline at end of file diff --git a/Samples/PacketInterceptor/DummyNostaleClient.cs b/Samples/PacketInterceptor/DummyNostaleClient.cs index 6b1da45..18e1dcb 100644 --- a/Samples/PacketInterceptor/DummyNostaleClient.cs +++ b/Samples/PacketInterceptor/DummyNostaleClient.cs @@ -1,38 +1,38 @@ -using NosCore.Packets; -using NosCore.Packets.ServerPackets.MiniMap; -using NosSmooth.Core.Client; -using NosSmooth.Core.Commands; -using NosSmooth.Core.Packets; -using Remora.Results; - -namespace PacketInterceptor; - -public class DummyNostaleClient : BaseNostaleClient -{ - private readonly IPacketHandler _packetHandler; - - public DummyNostaleClient(CommandProcessor commandProcessor, IPacketSerializer packetSerializer, - IPacketHandler packetHandler) : base(commandProcessor, packetSerializer) - { - _packetHandler = packetHandler; - } - - public override async Task RunAsync(CancellationToken stopRequested = default) - { - await _packetHandler.HandleSentPacketAsync(new CMapPacket() - { Header = "t", Id = 2, IsValid = true, KeepAliveId = 123, MapType = true, Type = 0 }, stopRequested); - return Result.FromSuccess(); - } - - public override Task SendPacketAsync(string packetString, CancellationToken ct = default) - { - Console.WriteLine($"Sending packet {packetString}"); - return Task.FromResult(Result.FromSuccess()); - } - - public override Task ReceivePacketAsync(string packetString, CancellationToken ct = default) - { - Console.WriteLine($"Receiving packet {packetString}"); - return Task.FromResult(Result.FromSuccess()); - } +using NosCore.Packets; +using NosCore.Packets.ServerPackets.MiniMap; +using NosSmooth.Core.Client; +using NosSmooth.Core.Commands; +using NosSmooth.Core.Packets; +using Remora.Results; + +namespace PacketInterceptor; + +public class DummyNostaleClient : BaseNostaleClient +{ + private readonly IPacketHandler _packetHandler; + + public DummyNostaleClient(CommandProcessor commandProcessor, IPacketSerializer packetSerializer, + IPacketHandler packetHandler) : base(commandProcessor, packetSerializer) + { + _packetHandler = packetHandler; + } + + public override async Task RunAsync(CancellationToken stopRequested = default) + { + await _packetHandler.HandleSentPacketAsync(new CMapPacket() + { Header = "t", Id = 2, IsValid = true, KeepAliveId = 123, MapType = true, Type = 0 }, stopRequested); + return Result.FromSuccess(); + } + + public override Task SendPacketAsync(string packetString, CancellationToken ct = default) + { + Console.WriteLine($"Sending packet {packetString}"); + return Task.FromResult(Result.FromSuccess()); + } + + public override Task ReceivePacketAsync(string packetString, CancellationToken ct = default) + { + Console.WriteLine($"Receiving packet {packetString}"); + return Task.FromResult(Result.FromSuccess()); + } } \ No newline at end of file diff --git a/Samples/PacketInterceptor/PacketInterceptor.csproj b/Samples/PacketInterceptor/PacketInterceptor.csproj index f0a0e2a..b627bd3 100644 --- a/Samples/PacketInterceptor/PacketInterceptor.csproj +++ b/Samples/PacketInterceptor/PacketInterceptor.csproj @@ -1,15 +1,15 @@ - - - - Exe - net6.0 - enable - enable - 10 - - - - - - - + + + + Exe + net6.0 + enable + enable + 10 + + + + + + + diff --git a/Samples/PacketInterceptor/Program.cs b/Samples/PacketInterceptor/Program.cs index af72e2f..f0baed5 100644 --- a/Samples/PacketInterceptor/Program.cs +++ b/Samples/PacketInterceptor/Program.cs @@ -1,42 +1,42 @@ -using Microsoft.Extensions.DependencyInjection; -using NosCore.Packets; -using NosSmooth.Core.Client; -using NosSmooth.Core.Extensions; -using NosSmooth.Core.Packets; -using PacketInterceptor; - -class Program -{ - public static async Task Main() - { - var provider = new ServiceCollection() - .AddNostaleCore() - .AddSingleton() - .AddPacketResponder() - .BuildServiceProvider(); - - var deserializerProvider = provider.GetRequiredService(); - - foreach (var line in File.ReadAllLines("packet.log")) - { - var packetString = string.Join("",line.Skip(8+10)); - try - { - var result = deserializerProvider.GetServerSerializer().Deserialize(packetString); - - if (!result.IsSuccess) - { - Console.WriteLine($"Could not deserialize packet {packetString}"); - } - } - catch (Exception e) - { - } - } - - var packet = deserializerProvider.GetServerSerializer().Deserialize("sayitemt 1 441092 17 1 4964 TrozZes {%s} e_info 0 4964 7 9 0 25 797 889 528 12 210 0 100 1200000 -1 0 441092 9 1.17.100 1.15.4 2.26.11 2.20.71 3.25.190 3.13.16 4.2.17 12.34.25 11.43.38 8 0 6 33.1.1600.0.2 44.1.-4.0.1 104.3.8.0.2 4.0.80.0.1 3.0.80.0.1 105.2.4.7640.1"); - - var client = provider.GetRequiredService(); - await client.RunAsync(); - } +using Microsoft.Extensions.DependencyInjection; +using NosCore.Packets; +using NosSmooth.Core.Client; +using NosSmooth.Core.Extensions; +using NosSmooth.Core.Packets; +using PacketInterceptor; + +class Program +{ + public static async Task Main() + { + var provider = new ServiceCollection() + .AddNostaleCore() + .AddSingleton() + .AddPacketResponder() + .BuildServiceProvider(); + + var deserializerProvider = provider.GetRequiredService(); + + foreach (var line in File.ReadAllLines("packet.log")) + { + var packetString = string.Join("",line.Skip(8+10)); + try + { + var result = deserializerProvider.GetServerSerializer().Deserialize(packetString); + + if (!result.IsSuccess) + { + Console.WriteLine($"Could not deserialize packet {packetString}"); + } + } + catch (Exception e) + { + } + } + + var packet = deserializerProvider.GetServerSerializer().Deserialize("sayitemt 1 441092 17 1 4964 TrozZes {%s} e_info 0 4964 7 9 0 25 797 889 528 12 210 0 100 1200000 -1 0 441092 9 1.17.100 1.15.4 2.26.11 2.20.71 3.25.190 3.13.16 4.2.17 12.34.25 11.43.38 8 0 6 33.1.1600.0.2 44.1.-4.0.1 104.3.8.0.2 4.0.80.0.1 3.0.80.0.1 105.2.4.7640.1"); + + var client = provider.GetRequiredService(); + await client.RunAsync(); + } } \ No newline at end of file diff --git a/Samples/PacketInterceptor/TestResponder.cs b/Samples/PacketInterceptor/TestResponder.cs index 6f46ef3..376742c 100644 --- a/Samples/PacketInterceptor/TestResponder.cs +++ b/Samples/PacketInterceptor/TestResponder.cs @@ -1,22 +1,22 @@ -using NosCore.Packets.Interfaces; -using NosCore.Packets.ServerPackets.MiniMap; -using NosSmooth.Core.Client; -using NosSmooth.Core.Packets; -using Remora.Results; - -namespace PacketInterceptor; - -public class TestResponder : IEveryPacketResponder -{ - private readonly INostaleClient _client; - - public TestResponder(INostaleClient client) - { - _client = client; - } - - public async Task Respond(TPacket packet, CancellationToken ct = default) where TPacket : IPacket - { - return await _client.SendPacketAsync("test"); - } +using NosCore.Packets.Interfaces; +using NosCore.Packets.ServerPackets.MiniMap; +using NosSmooth.Core.Client; +using NosSmooth.Core.Packets; +using Remora.Results; + +namespace PacketInterceptor; + +public class TestResponder : IEveryPacketResponder +{ + private readonly INostaleClient _client; + + public TestResponder(INostaleClient client) + { + _client = client; + } + + public async Task Respond(TPacket packet, CancellationToken ct = default) where TPacket : IPacket + { + return await _client.SendPacketAsync("test"); + } } \ No newline at end of file diff --git a/Samples/PacketLogger/App.xaml b/Samples/PacketLogger/App.xaml index 8486a28..bf38618 100644 --- a/Samples/PacketLogger/App.xaml +++ b/Samples/PacketLogger/App.xaml @@ -1,9 +1,9 @@ - - - - - + + + + + diff --git a/Samples/PacketLogger/App.xaml.cs b/Samples/PacketLogger/App.xaml.cs index 72f0c1b..437ecfd 100644 --- a/Samples/PacketLogger/App.xaml.cs +++ b/Samples/PacketLogger/App.xaml.cs @@ -1,17 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; - -namespace PacketLogger -{ - /// - /// Interaction logic for App.xaml - /// - public partial class App : Application - { - } +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace PacketLogger +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } } \ No newline at end of file diff --git a/Samples/PacketLogger/AssemblyInfo.cs b/Samples/PacketLogger/AssemblyInfo.cs index 4a05c7d..5d08a02 100644 --- a/Samples/PacketLogger/AssemblyInfo.cs +++ b/Samples/PacketLogger/AssemblyInfo.cs @@ -1,10 +1,10 @@ -using System.Windows; - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) )] \ No newline at end of file diff --git a/Samples/PacketLogger/MainWindow.xaml b/Samples/PacketLogger/MainWindow.xaml index 5f20bf8..205d8f8 100644 --- a/Samples/PacketLogger/MainWindow.xaml +++ b/Samples/PacketLogger/MainWindow.xaml @@ -1,12 +1,12 @@ - - - - - + + + + + diff --git a/Samples/PacketLogger/MainWindow.xaml.cs b/Samples/PacketLogger/MainWindow.xaml.cs index 9581893..440a96a 100644 --- a/Samples/PacketLogger/MainWindow.xaml.cs +++ b/Samples/PacketLogger/MainWindow.xaml.cs @@ -1,28 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -namespace PacketLogger -{ - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow : Window - { - public MainWindow() - { - InitializeComponent(); - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace PacketLogger +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + } + } } \ No newline at end of file diff --git a/Samples/PacketLogger/PacketLogger.csproj b/Samples/PacketLogger/PacketLogger.csproj index 277ebcd..eaa69b1 100644 --- a/Samples/PacketLogger/PacketLogger.csproj +++ b/Samples/PacketLogger/PacketLogger.csproj @@ -1,18 +1,18 @@ - - - - net6.0-windows - enable - true - 10 - - - - - - - - - - - + + + + net6.0-windows + enable + true + 10 + + + + + + + + + + + diff --git a/Samples/PacketLogger/Packets/PacketLoggerResponder.cs b/Samples/PacketLogger/Packets/PacketLoggerResponder.cs index bb58180..047ab6b 100644 --- a/Samples/PacketLogger/Packets/PacketLoggerResponder.cs +++ b/Samples/PacketLogger/Packets/PacketLoggerResponder.cs @@ -1,27 +1,27 @@ -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using NosCore.Packets; -using NosCore.Packets.Interfaces; -using NosSmooth.Core.Packets; -using Remora.Results; - -namespace PacketLogger.Packets; - -public class PacketLoggerResponder : IEveryPacketResponder -{ - private readonly ILogger _logger; - private readonly Serializer _serializer; - - public PacketLoggerResponder(ILogger logger, Serializer serializer) - { - _logger = logger; - _serializer = serializer; - } - - public Task Respond(TPacket packet, CancellationToken ct = default) where TPacket : IPacket - { - _logger.LogInformation(_serializer.Serialize(packet)); - return Task.FromResult(Result.FromSuccess()); - } +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using NosCore.Packets; +using NosCore.Packets.Interfaces; +using NosSmooth.Core.Packets; +using Remora.Results; + +namespace PacketLogger.Packets; + +public class PacketLoggerResponder : IEveryPacketResponder +{ + private readonly ILogger _logger; + private readonly Serializer _serializer; + + public PacketLoggerResponder(ILogger logger, Serializer serializer) + { + _logger = logger; + _serializer = serializer; + } + + public Task Respond(TPacket packet, CancellationToken ct = default) where TPacket : IPacket + { + _logger.LogInformation(_serializer.Serialize(packet)); + return Task.FromResult(Result.FromSuccess()); + } } \ No newline at end of file diff --git a/Samples/SimpleChat/DllMain.cs b/Samples/SimpleChat/DllMain.cs index d94174c..96a1381 100644 --- a/Samples/SimpleChat/DllMain.cs +++ b/Samples/SimpleChat/DllMain.cs @@ -4,15 +4,15 @@ // Copyright (c) František Boháček. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using System.Runtime.InteropServices; - +using System.Runtime.InteropServices; + namespace SimpleChat; /// /// The main entrypoint class of the dll. /// public class DllMain -{ +{ [DllImport("kernel32")] #pragma warning disable SA1600 public static extern bool AllocConsole(); @@ -24,7 +24,7 @@ public class DllMain /// The handle of the module. [DllExport] public static void Main(IntPtr handle) - { + { AllocConsole(); Console.WriteLine("Hello from SimpleChat DllMain entry point."); diff --git a/Samples/SimpleChat/FodyWeavers.xml b/Samples/SimpleChat/FodyWeavers.xml index a5dcf04..f00ec6d 100644 --- a/Samples/SimpleChat/FodyWeavers.xml +++ b/Samples/SimpleChat/FodyWeavers.xml @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/Samples/SimpleChat/SimpleChat.csproj b/Samples/SimpleChat/SimpleChat.csproj index ad507d5..46e0ab1 100644 --- a/Samples/SimpleChat/SimpleChat.csproj +++ b/Samples/SimpleChat/SimpleChat.csproj @@ -1,67 +1,67 @@ - - - net48 - enable - enable - 10 - - - 89E4EE92-5848-4390-A6A7-34972FE923F5 - DllExport.dll - SimpleChat - true - x86 - 7 - false - false - false - false - 30000 - 2 - 0 - 0 - 0 - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - 1.7.4 - false - 1 - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) - False - False - - - - - - + + + net48 + enable + enable + 10 + + + 89E4EE92-5848-4390-A6A7-34972FE923F5 + DllExport.dll + SimpleChat + true + x86 + 7 + false + false + false + false + 30000 + 2 + 0 + 0 + 0 + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + 1.7.4 + false + 1 + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) + False + False + + + + + + \ No newline at end of file diff --git a/Samples/WalkCommands/ChatPacketInterceptor.cs b/Samples/WalkCommands/ChatPacketInterceptor.cs index 9abcfc1..66ffd97 100644 --- a/Samples/WalkCommands/ChatPacketInterceptor.cs +++ b/Samples/WalkCommands/ChatPacketInterceptor.cs @@ -1,106 +1,106 @@ -// -// ChatPacketInterceptor.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using NosCore.Packets.Enumerations; -using NosCore.Packets.ServerPackets.Chats; -using NosSmooth.Core.Client; -using NosSmooth.Core.Commands; -using NosSmooth.Core.Extensions; -using NosSmooth.LocalClient; -using Remora.Results; -using WalkCommands.Commands; - -namespace WalkCommands; - -/// -/// Interceptor of chat commands. -/// -public class ChatPacketInterceptor : IPacketInterceptor -{ - private readonly IServiceProvider _provider; - private readonly ILogger _logger; - private readonly INostaleClient _client; - - /// - /// Initializes a new instance of the class. - /// - /// The service provider. - /// The logger. - /// The nostale client. - public ChatPacketInterceptor(IServiceProvider provider, ILogger logger, INostaleClient client) - { - _provider = provider; - _logger = logger; - _client = client; - } - - /// - public bool InterceptSend(ref string packet) - { - if (packet.StartsWith($"say #")) - { - var packetString = packet; - Task.Run(async () => - { - try - { - await ExecuteCommand(packetString.Substring(5)); - } - catch (Exception ex) - { - _logger.LogError(ex, "Could not execute command."); - } - }); - return false; - } - - return true; - } - - /// - public bool InterceptReceive(ref string packet) - { - return true; - } - - private async Task ExecuteCommand(string command) - { - await _client.ReceivePacketAsync(new SayPacket - { - Type = SayColorType.Green, Message = $"Handling a command {command}." - }); - - var splitted = command.Split(new[] { ' ' }); - using var scope = _provider.CreateScope(); - Result result; - switch (splitted[0]) - { - case "walk": - var walkCommand = scope.ServiceProvider.GetRequiredService(); - result = await walkCommand.HandleWalkToAsync(int.Parse(splitted[1]), int.Parse(splitted[2]), splitted.Length > 3 ? bool.Parse(splitted[3]) : true); - break; - case "detach": - var detachCommand = scope.ServiceProvider.GetRequiredService(); - result = await detachCommand.HandleDetach(); - break; - default: - await _client.ReceivePacketAsync(new SayPacket - { - Type = SayColorType.Red, Message = $"The command {splitted[0]} was not found." - }); - return; - } - - if (!result.IsSuccess) - { - _logger.LogError("Could not execute a command"); - _logger.LogResultError(result); - } - } +// +// ChatPacketInterceptor.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NosCore.Packets.Enumerations; +using NosCore.Packets.ServerPackets.Chats; +using NosSmooth.Core.Client; +using NosSmooth.Core.Commands; +using NosSmooth.Core.Extensions; +using NosSmooth.LocalClient; +using Remora.Results; +using WalkCommands.Commands; + +namespace WalkCommands; + +/// +/// Interceptor of chat commands. +/// +public class ChatPacketInterceptor : IPacketInterceptor +{ + private readonly IServiceProvider _provider; + private readonly ILogger _logger; + private readonly INostaleClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + /// The logger. + /// The nostale client. + public ChatPacketInterceptor(IServiceProvider provider, ILogger logger, INostaleClient client) + { + _provider = provider; + _logger = logger; + _client = client; + } + + /// + public bool InterceptSend(ref string packet) + { + if (packet.StartsWith($"say #")) + { + var packetString = packet; + Task.Run(async () => + { + try + { + await ExecuteCommand(packetString.Substring(5)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Could not execute command."); + } + }); + return false; + } + + return true; + } + + /// + public bool InterceptReceive(ref string packet) + { + return true; + } + + private async Task ExecuteCommand(string command) + { + await _client.ReceivePacketAsync(new SayPacket + { + Type = SayColorType.Green, Message = $"Handling a command {command}." + }); + + var splitted = command.Split(new[] { ' ' }); + using var scope = _provider.CreateScope(); + Result result; + switch (splitted[0]) + { + case "walk": + var walkCommand = scope.ServiceProvider.GetRequiredService(); + result = await walkCommand.HandleWalkToAsync(int.Parse(splitted[1]), int.Parse(splitted[2]), splitted.Length > 3 ? bool.Parse(splitted[3]) : true); + break; + case "detach": + var detachCommand = scope.ServiceProvider.GetRequiredService(); + result = await detachCommand.HandleDetach(); + break; + default: + await _client.ReceivePacketAsync(new SayPacket + { + Type = SayColorType.Red, Message = $"The command {splitted[0]} was not found." + }); + return; + } + + if (!result.IsSuccess) + { + _logger.LogError("Could not execute a command"); + _logger.LogResultError(result); + } + } } \ No newline at end of file diff --git a/Samples/WalkCommands/Commands/DetachCommand.cs b/Samples/WalkCommands/Commands/DetachCommand.cs index 5e47ecc..cf21d6f 100644 --- a/Samples/WalkCommands/Commands/DetachCommand.cs +++ b/Samples/WalkCommands/Commands/DetachCommand.cs @@ -1,53 +1,53 @@ -// -// DetachCommand.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using NosCore.Packets.Enumerations; -using NosCore.Packets.ServerPackets.Chats; -using NosSmooth.Core.Client; -using Remora.Results; - -namespace WalkCommands.Commands; - -/// -/// Group for detaching command that detaches the dll. -/// -public class DetachCommand -{ - private readonly CancellationTokenSource _dllStop; - private readonly INostaleClient _client; - - /// - /// Initializes a new instance of the class. - /// - /// The cancellation token source to stop the client. - /// The nostale client. - public DetachCommand(CancellationTokenSource dllStop, INostaleClient client) - { - _dllStop = dllStop; - _client = client; - } - - /// - /// Detach the dll. - /// - /// A result that may or may not have succeeded. - public async Task HandleDetach() - { - var receiveResult = await _client.ReceivePacketAsync(new SayPacket - { - Message = "Going to detach!", - Type = SayColorType.Green - }); - - if (!receiveResult.IsSuccess) - { - return receiveResult; - } - - _dllStop.Cancel(); - return Result.FromSuccess(); - } +// +// DetachCommand.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using NosCore.Packets.Enumerations; +using NosCore.Packets.ServerPackets.Chats; +using NosSmooth.Core.Client; +using Remora.Results; + +namespace WalkCommands.Commands; + +/// +/// Group for detaching command that detaches the dll. +/// +public class DetachCommand +{ + private readonly CancellationTokenSource _dllStop; + private readonly INostaleClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// The cancellation token source to stop the client. + /// The nostale client. + public DetachCommand(CancellationTokenSource dllStop, INostaleClient client) + { + _dllStop = dllStop; + _client = client; + } + + /// + /// Detach the dll. + /// + /// A result that may or may not have succeeded. + public async Task HandleDetach() + { + var receiveResult = await _client.ReceivePacketAsync(new SayPacket + { + Message = "Going to detach!", + Type = SayColorType.Green + }); + + if (!receiveResult.IsSuccess) + { + return receiveResult; + } + + _dllStop.Cancel(); + return Result.FromSuccess(); + } } \ No newline at end of file diff --git a/Samples/WalkCommands/Commands/WalkCommands.cs b/Samples/WalkCommands/Commands/WalkCommands.cs index 08b139b..9b2e293 100644 --- a/Samples/WalkCommands/Commands/WalkCommands.cs +++ b/Samples/WalkCommands/Commands/WalkCommands.cs @@ -1,77 +1,77 @@ -// -// WalkCommands.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using NosCore.Packets.Enumerations; -using NosCore.Packets.ServerPackets.Chats; -using NosSmooth.Core.Client; -using NosSmooth.Core.Commands; -using Remora.Results; - -namespace WalkCommands.Commands; - -/// -/// Represents command group for walking. -/// -public class WalkCommands -{ - private readonly INostaleClient _client; - - /// - /// Initializes a new instance of the class. - /// - /// The nostale client. - public WalkCommands(INostaleClient client) - { - _client = client ?? throw new ArgumentNullException(nameof(client)); - } - - /// - /// Attempts to walk the character to the specified lcoation. - /// - /// The x coordinate. - /// The y coordinate. - /// Whether the user can cancel the operation. - /// The cancellation token for cancelling the operation. - /// A result that may or may not have succeeded. - public async Task HandleWalkToAsync - ( - int x, - int y, - bool isCancellable = true, - CancellationToken ct = default - ) - { - var receiveResult = await _client.ReceivePacketAsync - ( - new SayPacket - { - Type = SayColorType.Red, Message = $"Going to walk to {x} {y}" - }, - ct - ); - - if (!receiveResult.IsSuccess) - { - return receiveResult; - } - - var command = new WalkCommand(x, y, isCancellable); - var walkResult = await _client.SendCommandAsync(command, ct); - if (!walkResult.IsSuccess) - { - return walkResult; - } - - return await _client.ReceivePacketAsync - ( - new SayPacket - { - Type = SayColorType.Red, Message = "Walk has finished successfully." - }, - ct - ); - } +// +// WalkCommands.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using NosCore.Packets.Enumerations; +using NosCore.Packets.ServerPackets.Chats; +using NosSmooth.Core.Client; +using NosSmooth.Core.Commands; +using Remora.Results; + +namespace WalkCommands.Commands; + +/// +/// Represents command group for walking. +/// +public class WalkCommands +{ + private readonly INostaleClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// The nostale client. + public WalkCommands(INostaleClient client) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + } + + /// + /// Attempts to walk the character to the specified lcoation. + /// + /// The x coordinate. + /// The y coordinate. + /// Whether the user can cancel the operation. + /// The cancellation token for cancelling the operation. + /// A result that may or may not have succeeded. + public async Task HandleWalkToAsync + ( + int x, + int y, + bool isCancellable = true, + CancellationToken ct = default + ) + { + var receiveResult = await _client.ReceivePacketAsync + ( + new SayPacket + { + Type = SayColorType.Red, Message = $"Going to walk to {x} {y}" + }, + ct + ); + + if (!receiveResult.IsSuccess) + { + return receiveResult; + } + + var command = new WalkCommand(x, y, isCancellable); + var walkResult = await _client.SendCommandAsync(command, ct); + if (!walkResult.IsSuccess) + { + return walkResult; + } + + return await _client.ReceivePacketAsync + ( + new SayPacket + { + Type = SayColorType.Red, Message = "Walk has finished successfully." + }, + ct + ); + } } \ No newline at end of file diff --git a/Samples/WalkCommands/DllMain.cs b/Samples/WalkCommands/DllMain.cs index 08460f8..b732493 100644 --- a/Samples/WalkCommands/DllMain.cs +++ b/Samples/WalkCommands/DllMain.cs @@ -1,40 +1,40 @@ -// -// DllMain.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Runtime.InteropServices; - -namespace WalkCommands; - -/// -/// Represents the dll entrypoint class. -/// -public class DllMain -{ - [DllImport("kernel32")] -#pragma warning disable SA1600 - public static extern bool AllocConsole(); -#pragma warning restore SA1600 - - /// - /// Represents the dll entrypoint method. - /// - [DllExport] - public static void Main() - { - AllocConsole(); - new Thread(() => - { - try - { - new Startup().RunAsync().GetAwaiter().GetResult(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - }).Start(); - } +// +// DllMain.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Runtime.InteropServices; + +namespace WalkCommands; + +/// +/// Represents the dll entrypoint class. +/// +public class DllMain +{ + [DllImport("kernel32")] +#pragma warning disable SA1600 + public static extern bool AllocConsole(); +#pragma warning restore SA1600 + + /// + /// Represents the dll entrypoint method. + /// + [DllExport] + public static void Main() + { + AllocConsole(); + new Thread(() => + { + try + { + new Startup().RunAsync().GetAwaiter().GetResult(); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + }).Start(); + } } \ No newline at end of file diff --git a/Samples/WalkCommands/FodyWeavers.xml b/Samples/WalkCommands/FodyWeavers.xml index 5029e70..f1dea8f 100644 --- a/Samples/WalkCommands/FodyWeavers.xml +++ b/Samples/WalkCommands/FodyWeavers.xml @@ -1,3 +1,3 @@ - - + + \ No newline at end of file diff --git a/Samples/WalkCommands/Startup.cs b/Samples/WalkCommands/Startup.cs index 35ba79c..200ba42 100644 --- a/Samples/WalkCommands/Startup.cs +++ b/Samples/WalkCommands/Startup.cs @@ -1,51 +1,51 @@ -// -// Startup.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using NosSmooth.Core.Client; -using NosSmooth.LocalClient; -using NosSmooth.LocalClient.Extensions; -using WalkCommands.Commands; - -namespace WalkCommands; - -/// -/// Startup class of WalkCommands. -/// -public class Startup -{ - private IServiceProvider BuildServices() - { - return new ServiceCollection() - .AddLocalClient() - .AddScoped() - .AddScoped() - .AddSingleton() - .Configure(o => o.AllowIntercept = true) - .AddSingleton() - .AddLogging(b => - { - b.ClearProviders(); - b.AddConsole(); - b.SetMinimumLevel(LogLevel.Debug); - }) - .BuildServiceProvider(); - } - - /// - /// Run the MoveToMiniland. - /// - /// A task that may or may not have succeeded. - public async Task RunAsync() - { - var provider = BuildServices(); - var mainCancellation = provider.GetRequiredService(); - - var client = provider.GetRequiredService(); - await client.RunAsync(mainCancellation.Token); - } +// +// Startup.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NosSmooth.Core.Client; +using NosSmooth.LocalClient; +using NosSmooth.LocalClient.Extensions; +using WalkCommands.Commands; + +namespace WalkCommands; + +/// +/// Startup class of WalkCommands. +/// +public class Startup +{ + private IServiceProvider BuildServices() + { + return new ServiceCollection() + .AddLocalClient() + .AddScoped() + .AddScoped() + .AddSingleton() + .Configure(o => o.AllowIntercept = true) + .AddSingleton() + .AddLogging(b => + { + b.ClearProviders(); + b.AddConsole(); + b.SetMinimumLevel(LogLevel.Debug); + }) + .BuildServiceProvider(); + } + + /// + /// Run the MoveToMiniland. + /// + /// A task that may or may not have succeeded. + public async Task RunAsync() + { + var provider = BuildServices(); + var mainCancellation = provider.GetRequiredService(); + + var client = provider.GetRequiredService(); + await client.RunAsync(mainCancellation.Token); + } } \ No newline at end of file diff --git a/Samples/WalkCommands/WalkCommands.csproj b/Samples/WalkCommands/WalkCommands.csproj index cfcbb16..dbd524a 100644 --- a/Samples/WalkCommands/WalkCommands.csproj +++ b/Samples/WalkCommands/WalkCommands.csproj @@ -1,76 +1,76 @@ - - - net48 - enable - enable - WalkCommands - WalkCommands - 10 - - - 9C088A1D-54DE-4A9B-9C1B-DBC5BD5F5299 - DllExport.dll - WalkCommands - true - x86 - 7 - false - false - false - false - 30000 - 2 - 0 - 0 - 0 - - - - 5.7.0 - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - 1.7.4 - false - 1 - - - 6.6.0 - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - 6.0.0 - - - 6.0.0 - - - 6.0.0 - - - - - - - - - - - - - - - - - $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) - False - False - - - - - - + + + net48 + enable + enable + WalkCommands + WalkCommands + 10 + + + 9C088A1D-54DE-4A9B-9C1B-DBC5BD5F5299 + DllExport.dll + WalkCommands + true + x86 + 7 + false + false + false + false + 30000 + 2 + 0 + 0 + 0 + + + + 5.7.0 + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + 1.7.4 + false + 1 + + + 6.6.0 + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + 6.0.0 + + + 6.0.0 + + + 6.0.0 + + + + + + + + + + + + + + + + + $(SolutionDir)packages\DllExport.1.7.4\gcache\$(DllExportMetaXBase)\$(DllExportNamespace)\$(DllExportMetaLibName) + False + False + + + + + + \ No newline at end of file diff --git a/Tests/NosSmooth.Core.Tests/NosSmooth.Core.Tests.csproj b/Tests/NosSmooth.Core.Tests/NosSmooth.Core.Tests.csproj index bf0dfc3..5a93821 100644 --- a/Tests/NosSmooth.Core.Tests/NosSmooth.Core.Tests.csproj +++ b/Tests/NosSmooth.Core.Tests/NosSmooth.Core.Tests.csproj @@ -1,27 +1,27 @@ - - - - net6.0 - enable - - false - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - + + + + net6.0 + enable + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/Tests/NosSmooth.Core.Tests/Packets/InPacketSerializerTest.cs b/Tests/NosSmooth.Core.Tests/Packets/InPacketSerializerTest.cs index 8e5f73b..d66baac 100644 --- a/Tests/NosSmooth.Core.Tests/Packets/InPacketSerializerTest.cs +++ b/Tests/NosSmooth.Core.Tests/Packets/InPacketSerializerTest.cs @@ -1,158 +1,158 @@ -// -// InPacketSerializerTest.cs -// -// Copyright (c) František Boháček. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using NosCore.Packets.ServerPackets.Inventory; -using NosCore.Packets.ServerPackets.Visibility; -using NosCore.Shared.Enumerations; -using NosSmooth.Core.Packets; -using NosSmooth.Core.Packets.Converters; -using Xunit; - -namespace NosSmooth.Core.Tests.Packets; - -/// -/// Test class for . -/// -public class InPacketSerializerTest -{ - private readonly InPacketSerializer _inPacketSerializer; - - /// - /// Initializes a new instance of the class. - /// - public InPacketSerializerTest() - { - var types = new List(new[] - { - typeof(InPacket), - typeof(InAliveSubPacket), - typeof(InNonPlayerSubPacket), - typeof(InCharacterSubPacket), - typeof(InItemSubPacket), - typeof(InEquipmentSubPacket), - typeof(UpgradeRareSubPacket), - typeof(FamilySubPacket), - }); - - _inPacketSerializer = new ServiceCollection() - .AddSingleton( - p => new PacketSerializerProvider(types, types, p) - ) - .AddSingleton() - .BuildServiceProvider() - .GetRequiredService(); - } - - /// - /// Tests whether the serializer accepts to handle in packet. - /// - [Fact] - public void AcceptsInPacket() - { - var shouldHandle = _inPacketSerializer.ShouldHandle( - "in 1 dfrfgh - 1 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 100 100 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0"); - Assert.True(shouldHandle); - } - - /// - /// Tests whether the serializer doesnt accept to handle non in packet. - /// - [Fact] - public void DoesntAcceptNonInPacket() - { - var shouldHandle = _inPacketSerializer.ShouldHandle( - "sr 5"); - Assert.False(shouldHandle); - } - - /// - /// Tests whether the result is successful when serializing player in packet. - /// - [Fact] - public void SucceedsDeserializingPlayerIn() - { - var result = _inPacketSerializer.Deserialize( - "in 1 dfrfgh - 1 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 50 98 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0" - ); - Assert.True(result.IsSuccess); - } - - /// - /// Tests whether the result is successful when serializing monster in packet. - /// - [Fact] - public void SucceedsDeserializingMonsterIn() - { - var result = _inPacketSerializer.Deserialize( - "in 2 334 1992 134 112 2 100 100 0 0 0 -1 1 0 -1 - 0 -1 0 0 0 0 0 0 0 0 0 0" - ); - Assert.True(result.IsSuccess); - } - - /// - /// Tests whether the result of deserializing player is correct. - /// - [Fact] - public void DeserializesPlayerInCorrectly() - { - var result = _inPacketSerializer.Deserialize( - "in 1 dfrfgh - 55 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 50 95 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0" - ); // 55 is id, 50 hp, 95 mp - - Assert.True(result.IsSuccess); - var inPacket = result.Entity; - - Assert.Equal(VisualType.Player, inPacket.VisualType); - Assert.NotNull(inPacket.Name); - Assert.Matches("dfrfgh", inPacket.Name); - Assert.Equal(55, inPacket.VisualId); - Assert.Equal(79, inPacket.PositionX); - Assert.Equal(2, inPacket.PositionY); - Assert.NotNull(inPacket.Direction); - Assert.Equal(6, (byte)inPacket.Direction!); - Assert.NotNull(inPacket.InCharacterSubPacket); - var characterSubPacket = inPacket.InCharacterSubPacket!; - Assert.Equal(AuthorityType.GameMaster, characterSubPacket.Authority); - Assert.Equal(CharacterClassType.Archer, characterSubPacket.Class); - Assert.NotNull(characterSubPacket.InAliveSubPacket); - Assert.Equal(50, characterSubPacket.InAliveSubPacket!.Hp); - Assert.Equal(95, characterSubPacket.InAliveSubPacket!.Mp); - - // TODO: check other things - } - - /// - /// Tests whether the result of deserializing monster is correct. - /// - [Fact] - public void DeserializesMonsterInCorrectly() - { - var result = _inPacketSerializer.Deserialize( - "in 2 334 1992 134 112 2 100 80 0 0 0 -1 1 0 -1 - 0 -1 0 0 0 0 0 0 0 0 0 0" - ); - Assert.True(result.IsSuccess); - var inPacket = result.Entity; - Assert.Equal(VisualType.Npc, inPacket.VisualType); - Assert.NotNull(inPacket.VNum); - Assert.Equal(334, inPacket.VNum!.Value); - Assert.Equal(1992, inPacket.VisualId); - Assert.Equal(134, inPacket.PositionX); - Assert.Equal(112, inPacket.PositionY); - Assert.NotNull(inPacket.Direction); - Assert.Equal(2, (byte)inPacket.Direction!); - Assert.NotNull(inPacket.InNonPlayerSubPacket); - var nonPlayerSubPacket = inPacket.InNonPlayerSubPacket!; - Assert.NotNull(nonPlayerSubPacket.InAliveSubPacket); - Assert.Equal(100, nonPlayerSubPacket.InAliveSubPacket!.Hp); - Assert.Equal(80, nonPlayerSubPacket.InAliveSubPacket!.Mp); - - // TODO: check other things - } +// +// InPacketSerializerTest.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using NosCore.Packets.ServerPackets.Inventory; +using NosCore.Packets.ServerPackets.Visibility; +using NosCore.Shared.Enumerations; +using NosSmooth.Core.Packets; +using NosSmooth.Core.Packets.Converters; +using Xunit; + +namespace NosSmooth.Core.Tests.Packets; + +/// +/// Test class for . +/// +public class InPacketSerializerTest +{ + private readonly InPacketSerializer _inPacketSerializer; + + /// + /// Initializes a new instance of the class. + /// + public InPacketSerializerTest() + { + var types = new List(new[] + { + typeof(InPacket), + typeof(InAliveSubPacket), + typeof(InNonPlayerSubPacket), + typeof(InCharacterSubPacket), + typeof(InItemSubPacket), + typeof(InEquipmentSubPacket), + typeof(UpgradeRareSubPacket), + typeof(FamilySubPacket), + }); + + _inPacketSerializer = new ServiceCollection() + .AddSingleton( + p => new PacketSerializerProvider(types, types, p) + ) + .AddSingleton() + .BuildServiceProvider() + .GetRequiredService(); + } + + /// + /// Tests whether the serializer accepts to handle in packet. + /// + [Fact] + public void AcceptsInPacket() + { + var shouldHandle = _inPacketSerializer.ShouldHandle( + "in 1 dfrfgh - 1 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 100 100 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0"); + Assert.True(shouldHandle); + } + + /// + /// Tests whether the serializer doesnt accept to handle non in packet. + /// + [Fact] + public void DoesntAcceptNonInPacket() + { + var shouldHandle = _inPacketSerializer.ShouldHandle( + "sr 5"); + Assert.False(shouldHandle); + } + + /// + /// Tests whether the result is successful when serializing player in packet. + /// + [Fact] + public void SucceedsDeserializingPlayerIn() + { + var result = _inPacketSerializer.Deserialize( + "in 1 dfrfgh - 1 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 50 98 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0" + ); + Assert.True(result.IsSuccess); + } + + /// + /// Tests whether the result is successful when serializing monster in packet. + /// + [Fact] + public void SucceedsDeserializingMonsterIn() + { + var result = _inPacketSerializer.Deserialize( + "in 2 334 1992 134 112 2 100 100 0 0 0 -1 1 0 -1 - 0 -1 0 0 0 0 0 0 0 0 0 0" + ); + Assert.True(result.IsSuccess); + } + + /// + /// Tests whether the result of deserializing player is correct. + /// + [Fact] + public void DeserializesPlayerInCorrectly() + { + var result = _inPacketSerializer.Deserialize( + "in 1 dfrfgh - 55 79 2 6 2 1 0 106 2 -1.4480.4452.4468.4840.4132.-1.-1.-1.-1 50 95 0 -1 4 4 0 43 0 0 108 108 -1 - 26 0 0 0 0 99 0 0|0|0 0 0 10 80 0" + ); // 55 is id, 50 hp, 95 mp + + Assert.True(result.IsSuccess); + var inPacket = result.Entity; + + Assert.Equal(VisualType.Player, inPacket.VisualType); + Assert.NotNull(inPacket.Name); + Assert.Matches("dfrfgh", inPacket.Name); + Assert.Equal(55, inPacket.VisualId); + Assert.Equal(79, inPacket.PositionX); + Assert.Equal(2, inPacket.PositionY); + Assert.NotNull(inPacket.Direction); + Assert.Equal(6, (byte)inPacket.Direction!); + Assert.NotNull(inPacket.InCharacterSubPacket); + var characterSubPacket = inPacket.InCharacterSubPacket!; + Assert.Equal(AuthorityType.GameMaster, characterSubPacket.Authority); + Assert.Equal(CharacterClassType.Archer, characterSubPacket.Class); + Assert.NotNull(characterSubPacket.InAliveSubPacket); + Assert.Equal(50, characterSubPacket.InAliveSubPacket!.Hp); + Assert.Equal(95, characterSubPacket.InAliveSubPacket!.Mp); + + // TODO: check other things + } + + /// + /// Tests whether the result of deserializing monster is correct. + /// + [Fact] + public void DeserializesMonsterInCorrectly() + { + var result = _inPacketSerializer.Deserialize( + "in 2 334 1992 134 112 2 100 80 0 0 0 -1 1 0 -1 - 0 -1 0 0 0 0 0 0 0 0 0 0" + ); + Assert.True(result.IsSuccess); + var inPacket = result.Entity; + Assert.Equal(VisualType.Npc, inPacket.VisualType); + Assert.NotNull(inPacket.VNum); + Assert.Equal(334, inPacket.VNum!.Value); + Assert.Equal(1992, inPacket.VisualId); + Assert.Equal(134, inPacket.PositionX); + Assert.Equal(112, inPacket.PositionY); + Assert.NotNull(inPacket.Direction); + Assert.Equal(2, (byte)inPacket.Direction!); + Assert.NotNull(inPacket.InNonPlayerSubPacket); + var nonPlayerSubPacket = inPacket.InNonPlayerSubPacket!; + Assert.NotNull(nonPlayerSubPacket.InAliveSubPacket); + Assert.Equal(100, nonPlayerSubPacket.InAliveSubPacket!.Hp); + Assert.Equal(80, nonPlayerSubPacket.InAliveSubPacket!.Mp); + + // TODO: check other things + } } \ No newline at end of file -- 2.49.0