Using NuGet Packages and a Database in a CounterStrikeSharp Plugin
Many useful plugins store data: bans, stats, ranks. For that you add a NuGet package to the project, and the most important rule is not to block the game while you wait for the database. This guide covers both, using Dapper and MySqlConnector as the example.
Add the packages
NuGet packages are listed in the project file. Dapper makes queries short and MySqlConnector talks to MariaDB and MySQL. Our compiler downloads them for you when it builds.
<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.*" />
<PackageReference Include="Dapper" Version="2.*" />
<PackageReference Include="MySqlConnector" Version="2.*" />
</ItemGroup>
What happens when you compile
The build produces your plugin DLL and, next to it, the DLLs of the packages your plugin needs. Files that CounterStrikeSharp already contains are separated into another folder, so you do not copy them twice.
What to copy to the server
Copy the plugin folder, with the extra package DLLs inside it, to the plugins folder of your server. Do not copy the dependencies folder, because the server already has those files and a second copy can cause conflicts.
Run a query without freezing the game
The game runs on one main thread. If you wait for a database there, the whole server stutters. Run the query in Task.Run, and when you need to touch the game again, return to the main thread with Server.NextFrame.
using CounterStrikeSharp.API;
using Dapper;
using Microsoft.Extensions.Logging;
using MySqlConnector;
public void CountPlayers()
{
Task.Run(async () =>
{
await using var connection = new MySqlConnection(Config.ConnectionString); var count = await connection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM players");
Server.NextFrame(() => {
Logger.LogInformation("Players in the database: {Count}", count);
});
});
}
Keep the connection string in the config
Do not write the address, user and password in the code. Put the connection string in the plugin config, as in our config guide, so each server owner uses their own database.
Packages that do not belong in a plugin
Some packages are too big or are not made to live inside a game server, for example web frameworks such as ASP.NET. Prefer small libraries, and if a package fails to load, check whether it needs native files that are missing.
Test before going live
Try the plugin on a test server with a test database first. Check that the tables are created, that a failed connection does not crash the plugin, and that the log gives a clear message when the database is down.
Was this tutorial useful?
Barlap for the community.