### Example Command Execution and Output Source: https://docs.cssharp.dev/docs/features/console-commands.html Illustrates the execution of a command with quoted arguments and its corresponding output, showing how parameters are parsed. ```text > custom_command "Test Quoted" 5 13 # Output Arg Count: 4 Arg String: "Test Quoted" 5 13 Command String: custom_command "Test Quoted" 5 13 First Argument: custom_command Second Argument: Test Quoted ``` -------------------------------- ### Verify CounterStrikeSharp Installation Source: https://docs.cssharp.dev/docs/guides/getting-started.html After installation, use this command to confirm CounterStrikeSharp is loaded as a plugin. It should show the plugin and its version. ```bash meta list Listing 1 plugin: [01] CounterStrikeSharp (0.1.0) by Roflmuffin ``` -------------------------------- ### Project directory structure example Source: https://docs.cssharp.dev/docs/guides/auto-build-and-deploy.html This illustrates the typical output directory structure after a build, located in `bin//` relative to your `.csproj` file. ```text projectDirectory ├── projectName.csproj ├── bin │ └── Debug │ └── net8.0 │ └── PLUGIN BUILDS HERE ``` -------------------------------- ### Verify Metamod Installation Source: https://docs.cssharp.dev/docs/guides/getting-started.html Run this command in the server console to check if Metamod is loaded. It should list at least one plugin. ```bash meta list ``` -------------------------------- ### Basic Hello World Plugin Code Source: https://docs.cssharp.dev/docs/guides/hello-world-plugin.html Implement the core logic for your plugin. This example defines the module name, version, and prints 'Hello World!' to the console when loaded. ```csharp using CounterStrikeSharp.API.Core; namespace HelloWorldPlugin; public class HelloWorldPlugin : BasePlugin { public override string ModuleName => "Hello World Plugin"; public override string ModuleVersion => "0.0.1"; public override void Load(bool hotReload) { Console.WriteLine("Hello World!"); } } ``` -------------------------------- ### Server Folder Structure Example Source: https://docs.cssharp.dev/docs/guides/getting-started.html This tree command displays the expected directory structure for CounterStrikeSharp and Metamod within the server's addons folder. Ensure your files match this layout. ```bash /game/csgo/addons > tree -L 2 addons ├── counterstrikesharp │ ├── api │ ├── bin │ ├── dotnet │ ├── plugins │ └── gamedata │ ├── metamod │ ├── bin │ ├── counterstrikesharp.vdf │ ├── metaplugins.ini │ └── README.txt ├── metamod.vdf └── metamod_x64.vdf ``` -------------------------------- ### Add CounterStrikeSharp API NuGet Package Source: https://docs.cssharp.dev/docs/guides/hello-world-plugin.html Alternatively, install the CounterStrikeSharp.API NuGet package using the dotnet CLI. This is often a more convenient way to manage dependencies. ```bash dotnet add package CounterStrikeSharp.API ``` -------------------------------- ### Define Admin Group with Permissions Source: https://docs.cssharp.dev/docs/admin-framework/defining-admin-groups.html Define a new admin group in `configs/admin_groups.json`. Group names must start with '#'. Permissions are listed under the 'flags' key. ```json #css/simple-admin": { "flags": [ "@css/generic", "@css/reservation", "@css/ban", "@css/slay", ] } ``` -------------------------------- ### Example of Dependency Injection in a Plugin Source: https://docs.cssharp.dev/docs/guides/dependency-injection.html Demonstrates injecting ILogger and a custom class (TestInjectedClass) into a plugin. Dependencies are injected into the plugin's constructor before the Load method is called. ```csharp public class TestInjectedClass { private readonly ILogger _logger; public TestInjectedClass(ILogger logger) { _logger = logger; } public void Hello() { _logger.LogInformation("Hello World from Test Injected Class"); } } public class TestPluginServiceCollection : IPluginServiceCollection { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddScoped(); } } public class SamplePlugin : BasePlugin { private readonly TestInjectedClass _testInjectedClass; public SamplePlugin(TestInjectedClass testInjectedClass) { _testInjectedClass = testInjectedClass; } public override void Load(bool hotReload) { _testInjectedClass.Hello(); } } ``` -------------------------------- ### Accessing Player Pawn from Controller Source: https://docs.cssharp.dev/docs/guides/referencing-players.html Demonstrates how to get the PlayerPawn object from a PlayerController. Use the `.Value` property to access the underlying object from a CHandle. ```csharp CCSPlayerController player = ...; CCSPlayerPawn playerPawn = player.PlayerPawn.Value; // as `PlayerPawn` is a `CHandle`, to fetch its underlying value we must get the `.Value` property CCSPlayerController samePlayer = playerPawn.Controller.Value; // same as above. ``` -------------------------------- ### Standard CounterStrikeSharp Permissions Source: https://docs.cssharp.dev/docs/admin-framework/defining-admins.html These are commonly used permission flags that can be assigned to admins. All custom and standard permissions must start with an '@' symbol. ```plaintext @css/reservation # Reserved slot access. @css/generic # Generic admin. @css/kick # Kick other players. @css/ban # Ban other players. @css/unban # Remove bans. @css/vip # General vip status. @css/slay # Slay/harm other players. @css/changemap # Change the map or major gameplay features. @css/cvar # Change most cvars. @css/config # Execute config files. @css/chat # Special chat privileges. @css/vote # Start or create votes. @css/password # Set a password on the server. @css/rcon # Use RCON commands. @css/cheats # Change sv_cheats or use cheating commands. @css/root # Magically enables all flags and ignores immunity values. ``` -------------------------------- ### Getting Player Controller from Event UserID Source: https://docs.cssharp.dev/docs/guides/referencing-players.html Shows how to directly obtain the PlayerController object from the Userid field in game events like EventPlayerSpawn. ```csharp RegisterEventHandler((@event, info) => { CCSPlayerController player = @event.Userid; }) ``` -------------------------------- ### Get and Set Primitive ConVar Values Source: https://docs.cssharp.dev/docs/features/console-variables.html Use `GetPrimitiveValue()` to get a reference to a primitive ConVar's value and modify it directly. The `SetValue(T)` helper provides a simpler way to set the value. ```csharp cheatsCvar.GetPrimitiveValue(); // false ``` ```csharp cheatsCvar.GetPrimitiveValue() = true; // false ``` ```csharp // You can also use the simplified helper: cheatsCvar.SetValue(true); ``` -------------------------------- ### Find a ConVar Source: https://docs.cssharp.dev/docs/features/console-variables.html Use the `ConVar.Find` static method to get a reference to an existing ConVar. It returns null if the ConVar is not found. ```csharp var cheatsCvar = ConVar.Find("sv_cheats"); ``` -------------------------------- ### Registering an OnEntitySpawned Listener Source: https://docs.cssharp.dev/docs/features/global-listeners.html Register a listener for the OnEntitySpawned event to react when an entity spawns. This example specifically targets 'smokegrenade_projectile' and modifies its color on the next server frame. ```csharp public override void Load(bool hotReload) { RegisterListener(entity => { if (entity.DesignerName != "smokegrenade_projectile") return; var projectile = new CSmokeGrenadeProjectile(entity.Handle); // Changes smoke grenade colour to a random colour each time. Server.NextFrame(() => { projectile.SmokeColor.X = Random.Shared.NextSingle() * 255.0f; projectile.SmokeColor.Y = Random.Shared.NextSingle() * 255.0f; projectile.SmokeColor.Z = Random.Shared.NextSingle() * 255.0f; Logger.LogInformation("Smoke grenade spawned with color {SmokeColor}", projectile.SmokeColor); }); }); } ``` -------------------------------- ### Create New Class Library Project Source: https://docs.cssharp.dev/docs/guides/hello-world-plugin.html Use the dotnet CLI to create a new class library project for your plugin. This sets up the basic project structure. ```bash dotnet new classlib --name HelloWorldPlugin ``` -------------------------------- ### Plugin File Structure Source: https://docs.cssharp.dev/docs/guides/hello-world-plugin.html After building, copy the generated .dll, .deps.json, and .pdb files into a new folder within the server's plugins directory. The folder name must match the .dll file name. ```text . └── HelloWorldPlugin ├── HelloWorldPlugin.deps.json ├── HelloWorldPlugin.dll └── HelloWorldPlugin.pdb ``` -------------------------------- ### Register Plugin Capabilities Source: https://docs.cssharp.dev/docs/features/shared-plugin-api.html Implement and register capabilities. Player capabilities receive the calling player context, while plugin capabilities can return a direct instance. ```csharp // Player capabilities are given the calling player context Capabilities.RegisterPlayerCapability(BalanceCapability, player => new BalanceHandler(player)); // Plugin capabilities can simply return an instance of the interface Capabilities.RegisterPluginCapability(BalanceServiceCapability, () => new BalanceService()); ``` -------------------------------- ### Build plugin on file changes with dotnet watch Source: https://docs.cssharp.dev/docs/guides/auto-build-and-deploy.html Use this command to automatically build your project whenever source files change. Ensure you specify the project file path. ```bash dotnet watch build --project path/to/projectName.csproj ``` -------------------------------- ### Build to a custom output directory Source: https://docs.cssharp.dev/docs/guides/auto-build-and-deploy.html Configure your `.csproj` file to specify a custom output directory for build artifacts using the `` property. This can simplify locating your plugin DLLs. ```xml ./build/$(MSBuildProjectName) ``` -------------------------------- ### Build to Windows filesystem from WSL Source: https://docs.cssharp.dev/docs/guides/auto-build-and-deploy.html When developing in WSL and using Windows-based tools like WinSCP, use this command to direct your build output to a path accessible from Windows. This allows WinSCP to monitor the build directory. ```bash dotnet watch build --project path/to/.csproj --property:OutDir=/mnt//some/path/ ``` -------------------------------- ### Define Plugin Services with IPluginServiceCollection Source: https://docs.cssharp.dev/docs/guides/dependency-injection.html Implement IPluginServiceCollection to configure services for your plugin. This allows adding scoped and singleton services to the DI container. ```csharp public class TestPlugin : BasePlugin { // Plugin code... } public class TestPluginServiceCollection : IPluginServiceCollection { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddScoped(); serviceCollection.AddLogging(builder => ...); } } ``` -------------------------------- ### Declare Player and Plugin Capabilities Source: https://docs.cssharp.dev/docs/features/shared-plugin-api.html Declare capabilities using static variables. Player capabilities are player-specific, while plugin capabilities are generic. Ensure the capability name matches when using the shared API. ```csharp public static PlayerCapability BalanceCapability { get; } = new("myplugin:balance"); public static PluginCapability BalanceServiceCapability { get; } = new("myplugin:balance_service"); ``` -------------------------------- ### Add CounterStrikeSharp API Reference to .csproj Source: https://docs.cssharp.dev/docs/guides/hello-world-plugin.html Manually add a reference to the CounterStrikeSharp.Api.dll in your project's .csproj file. Ensure theHintPath points to the correct location of the DLL. ```xml net8.0 enable enable [where you downloaded or installed]/addons/counterstrikesharp/api/CounterStrikeSharp.API.dll ``` -------------------------------- ### Validating Player Controller and Pawn Handles Source: https://docs.cssharp.dev/docs/guides/referencing-players.html Illustrates how to check if a PlayerController and its associated PlayerPawn are valid before attempting to access their properties. This prevents null reference exceptions. ```csharp RegisterEventHandler((@event, info) => { if (!@event.Userid.IsValid) return 0; // Checks that the PlayerController is valid if (!@event.Userid.PlayerPawn.IsValid) return 0; // Checks that the value of the CHandle is pointing to a valid PlayerPawn. }) ``` -------------------------------- ### Accessing Command Parameters Source: https://docs.cssharp.dev/docs/features/console-commands.html Demonstrates how to access command parameters like argument count, string, and specific arguments using the CommandInfo class within a console command callback. ```csharp [ConsoleCommand("custom_command", "This is an example command description")] public void OnCommand(CCSPlayerController? player, CommandInfo command) { Console.Write($"\ Arg Count: {command.ArgCount}\ Arg String: {command.ArgString}\ Command String: {command.GetCommandString}\ First Argument: {command.ArgByIndex(0)}\ Second Argument: {command.ArgByIndex(1)}"); } ``` -------------------------------- ### Define Admins in admins.json Source: https://docs.cssharp.dev/docs/admin-framework/defining-admins.html Add new admin entries to the `configs/admins.json` file. Each entry requires a unique key (e.g., admin name), an `identity` field for the SteamID, and a `flags` array specifying their permissions. ```json { "ZoNiCaL": { "identity": "76561198808392634", "flags": ["@css/changemap", "@css/generic"] }, "another ZoNiCaL": { "identity": "STEAM_0:1:1", "flags": ["@css/generic"] } } ``` -------------------------------- ### Use Registered Capabilities Source: https://docs.cssharp.dev/docs/features/shared-plugin-api.html Retrieve and use capabilities via the '.Get()' method. Always check the returned value for null, as it will be null if no plugin provides an implementation. ```csharp var balance = BalanceCapability.Get(player); var balanceService = BalanceServiceCapability.Get(); if (balance == null) return; balance.Add(500); ``` -------------------------------- ### Enable NuGet Resolver Configuration Source: https://docs.cssharp.dev/docs/features/shared-plugin-api.html Enable the NuGet dependency resolver by setting 'PluginResolveNugetPackages' to true in your core configuration. This feature is disabled by default. ```json { ... "PluginResolveNugetPackages": true ... ``` -------------------------------- ### Define Global Command Overrides Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Configure global command overrides in `configs/admin_overrides.json`. Specify new flags, whether the override is enabled, and the permission check type (`all` or `any`). ```json "css": { "flags": [ "@css/custom-permission" ], "check_type": "all", "enabled": true } ``` -------------------------------- ### Stacking Permission Attributes on a Command Source: https://docs.cssharp.dev/docs/admin-framework/admin-command-attributes.html Stack multiple RequiresPermissions and RequiresPermissionsOr attributes to enforce complex permission requirements. All attributes will be checked. ```csharp // Requires (@css/cvar AND @custom/permission-1) AND either (@custom/permission-1 OR @custom/permission-2). [RequiresPermissions("@css/cvar", "@custom/permission-1")] [RequiresPermissionsOr("@css/ban", "@custom/permission-2")] public void OnMyComplexCommand(CCSPlayerController? caller, CommandInfo info) { ... } ``` -------------------------------- ### CommandHelper Usage Message Source: https://docs.cssharp.dev/docs/features/console-commands.html Displays the expected usage message when a client attempts to execute a command without the required arguments, as defined by CommandHelper. ```text [CSS] Expected usage: "!freeze [target]". ``` -------------------------------- ### Retrieving Player from Identifiers Source: https://docs.cssharp.dev/docs/guides/referencing-players.html Provides utility methods to fetch a player's controller instance using their UserID, entity index, or slot. Ensure to validate handles before use. ```csharp var player = Utilities.GetPlayerFromUserid(userid); var player = Utilities.GetPlayerFromIndex(index); var player = Utilities.GetPlayerFromSlot(slot); ``` -------------------------------- ### Set Player Command Override in Code Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Programmatically set a command override for a specific player using `AdminManager.SetPlayerCommandOverride`. ```csharp AdminManager.SetPlayerCommandOverride(player, "command_name", true); ``` -------------------------------- ### Manual Game Event Listener Registration in OnLoad Source: https://docs.cssharp.dev/docs/features/game-events.html Register event listeners manually within the OnLoad method or any other method with access to the plugin instance. This provides flexibility in managing event subscriptions. ```csharp public override void Load(bool hotReload) { RegisterEventHandler((@event, info) => { Logger.LogInformation("Round has started with time limit of {Timelimit}", @event.Timelimit); return HookResult.Continue; }); } ``` -------------------------------- ### Register Console Command in OnLoad Source: https://docs.cssharp.dev/docs/features/console-commands.html Manually registers a console command within the OnLoad method of a plugin. This provides flexibility for command binding during plugin initialization. ```csharp public override void Load(bool hotReload) { AddCommand("on_load_command", "A command is registered during OnLoad", (player, info) => { if (player == null) return; Console.WriteLine($"Custom command called."); }); } ``` -------------------------------- ### Assign Admins to Groups Source: https://docs.cssharp.dev/docs/admin-framework/defining-admin-groups.html Assign admins to predefined groups using the 'groups' array in `configs/admins.json`. Admins inherit flags from their assigned groups. ```json { "erikj": { "identity": "76561198808392634", "flags": ["@mycustomplugin/admin"], "groups": ["#css/simple-admin"] }, "Another erikj": { "identity": "STEAM_0:1:1", "flags": ["@mycustomplugin/admin"], "groups": ["#css/simple-admin"] } } ``` -------------------------------- ### Assigning OR Permissions to a Command Source: https://docs.cssharp.dev/docs/admin-framework/admin-command-attributes.html Use the RequiresPermissionsOr attribute to allow a caller with at least one of the specified permissions. CounterStrikeSharp handles the checks automatically. ```csharp [RequiresPermissionsOr("@css/ban", "@custom/permission-2")] public void OnMyOtherCommand(CCSPlayerController? caller, CommandInfo info) { ... } ``` -------------------------------- ### Register Console Command with Attribute Source: https://docs.cssharp.dev/docs/features/console-commands.html Automatically registers a console command using the ConsoleCommand attribute. The command is managed automatically on hot reload. ```csharp [ConsoleCommand("custom_command", "This is an example command description")] public void OnCommand(CCSPlayerController? player, CommandInfo command) { if (player == null) { Console.WriteLine("Command has been called by the server."); return; } Console.WriteLine("Custom command called."); } ``` -------------------------------- ### Define Plugin API Contract Source: https://docs.cssharp.dev/docs/features/shared-plugin-api.html Define the shape of the API using interfaces in a shared library. This library should not contain business logic and must be placed in the 'shared' subfolder. ```csharp public interface IBalanceHandler { decimal Balance { get; } // These are just here to show that you can have methods on your shared types. // You could also add a Setter to the Balance property. public decimal Add(decimal amount); public decimal Subtract(decimal amount); } ``` -------------------------------- ### Assigning Required Permissions to a Command Source: https://docs.cssharp.dev/docs/admin-framework/admin-command-attributes.html Use the RequiresPermissions attribute to ensure a caller has all specified permissions. CounterStrikeSharp handles the checks automatically. ```csharp [RequiresPermissions("@css/slay", "@custom/permission")] public void OnMyCommand(CCSPlayerController? caller, CommandInfo info) { ... } ``` -------------------------------- ### Add Permission Override Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Add a new permission override for a command using `AdminManager.AddPermissionOverride`. ```csharp AdminManager.AddPermissionOverride("command_name", "new_permission", "all"); ``` -------------------------------- ### Automatic Game Event Listener Registration Source: https://docs.cssharp.dev/docs/features/game-events.html Use the GameEventHandler attribute on methods within BasePlugin to automatically register event listeners. These are managed automatically on hot reload. Ensure the first parameter is a subclass of GameEvent. ```csharp [GameEventHandler] public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info) { // Userid will give you a reference to a CCSPlayerController class. // Before accessing any of its fields, you must first check if the Userid // handle is actually valid, otherwise you may run into runtime exceptions. // See the documentation section on Referencing Players for details. if (@event.Userid.IsValid) { Logger.LogInformation("Player {Name} has connected!", @event.Userid.PlayerName); } return HookResult.Continue; } ``` -------------------------------- ### Override Command for Specific Admin Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Set command overrides for an individual admin in `configs/admins.json`. Set to `true` to allow execution, or `false` to deny. ```json { "ZoNiCaL": { "identity": "76561198808392634", "flags": ["@css/changemap", "@css/generic"], "immunity": 100, "command_overrides": { "example_command": true } } } ``` -------------------------------- ### CommandHelper Execution Restriction Message Source: https://docs.cssharp.dev/docs/features/console-commands.html Shows the message displayed to a user when they attempt to execute a command that is restricted to a different execution context (e.g., client trying to run a server-only command). ```text [CSS] This command can only be executed by clients. ``` -------------------------------- ### Assign Immunity to an Admin Source: https://docs.cssharp.dev/docs/admin-framework/defining-admin-immunity.html Define an admin's immunity level by adding the `immunity` key to their entry in `configs/admins.json`. Higher values indicate greater immunity. ```json { "ZoNiCaL": { "identity": "76561198808392634", "flags": ["@css/changemap", "@css/generic"], "immunity": 100 } } ``` -------------------------------- ### Override Command for Admin Group Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Define command overrides for an admin group in `configs/admin_groups.json`. Set to `true` to allow, or `false` to deny. ```json "#css/simple-admin": { "flags": [ "@css/generic", "@css/reservation", "@css/ban", "@css/slay", ], "command_overrides": { "example_command_2": false } } ``` -------------------------------- ### Set Command Override State Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Toggle the enabled state of a command override in code using `AdminManager.SetCommandOverrideState`. ```csharp AdminManager.SetCommandOverrideState("command_name", false); ``` -------------------------------- ### Assign Immunity to a Group Source: https://docs.cssharp.dev/docs/admin-framework/defining-admin-immunity.html Set a default immunity level for a group in `configs/admins.json`. Individual admins within the group will inherit this immunity if they don't have a specific value assigned. ```json "#css/simple-admin": { "flags": [ "@css/generic", "@css/reservation", "@css/ban", "@css/slay", ], "immunity": 100 } ``` -------------------------------- ### CommandUsage Enum Definition Source: https://docs.cssharp.dev/docs/features/console-commands.html Defines the possible values for the CommandUsage enum, which specifies who is allowed to execute a console command (client, server, or both). ```csharp public enum CommandUsage { CLIENT_AND_SERVER = 0, CLIENT_ONLY, SERVER_ONLY } ``` -------------------------------- ### Using CommandHelper Attribute for Validation Source: https://docs.cssharp.dev/docs/features/console-commands.html Applies the CommandHelper attribute to a console command method to enforce argument count and restrict execution to specific user types (client and server). ```csharp [ConsoleCommand("freeze", "Freezes a client.")] [CommandHelper(minArgs: 1, usage: "[target]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnFreezeCommand(CCSPlayerController? caller, CommandInfo command) { ... } ``` -------------------------------- ### Checking for Permission Groups Source: https://docs.cssharp.dev/docs/admin-framework/admin-command-attributes.html Use the RequiresPermissions attribute with a group identifier (prefixed with '#') to check if the caller belongs to any of the specified groups. ```csharp [RequiresPermissions("#css/simple-admin")] public void OnMyGroupCommand(CCSPlayerController? caller, CommandInfo info) { ... } ``` -------------------------------- ### Remove Permission Override Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Remove an existing permission override for a command using `AdminManager.RemovePermissionOverride`. ```csharp AdminManager.RemovePermissionOverride("command_name", "permission_to_remove"); ``` -------------------------------- ### Manipulate Native Object ConVar Values Source: https://docs.cssharp.dev/docs/features/console-variables.html Use `GetNativeValue()` to retrieve native objects from ConVars. You can then manipulate these objects directly. ```csharp var fogCvar = ConVar.Find("fog_color"); var fogColor = fogCvar.GetNativeValue(); Console.WriteLine($"fog_color = {fogColor}"); // You can then manipulate the vector as normal. fogColor.X = 0.12345; ``` -------------------------------- ### Check if Command is Overridden Source: https://docs.cssharp.dev/docs/admin-framework/defining-command-overrides.html Determine if a command has an active override using `AdminManager.CommandIsOverriden`. ```csharp AdminManager.CommandIsOverriden("command_name"); ``` -------------------------------- ### Manipulate String ConVar Values Source: https://docs.cssharp.dev/docs/features/console-variables.html Access and modify string ConVars using the `StringValue` property. This handles the necessary marshaling between C# and the server. ```csharp var stringCvar = ConVar.Find("sv_skyname"); Console.WriteLine($"sv_skyname = {stringCvar.StringValue}"); stringCvar.StringValue = "foobar"; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.