diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index adc6b2169..b397e9790 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,7 +5,7 @@ on: [push, pull_request] env: DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_NOLOGO: true - DOTNET_SDK_VERSION: 7.0.x + DOTNET_SDK_VERSION: 8.0 jobs: main: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f031de9d1..5414b2e25 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -4,8 +4,8 @@ on: [push, pull_request] env: CONFIGURATION: Release - DOTNET_SDK_VERSION: 7.0.x - NET_CORE_VERSION: net7.0 + DOTNET_SDK_VERSION: 8.0 + NET_CORE_VERSION: net8.0 NET_FRAMEWORK_VERSION: net481 NODE_JS_VERSION: 'lts/*' PLUGINS: ArchiSteamFarm.OfficialPlugins.ItemsMatcher ArchiSteamFarm.OfficialPlugins.MobileAuthenticator ArchiSteamFarm.OfficialPlugins.SteamTokenDumper diff --git a/ArchiSteamFarm.CustomPlugins.SignInWithSteam/Data/SignInWithSteamResponse.cs b/ArchiSteamFarm.CustomPlugins.SignInWithSteam/Data/SignInWithSteamResponse.cs index b24ccccab..d8348fa44 100644 --- a/ArchiSteamFarm.CustomPlugins.SignInWithSteam/Data/SignInWithSteamResponse.cs +++ b/ArchiSteamFarm.CustomPlugins.SignInWithSteam/Data/SignInWithSteamResponse.cs @@ -28,5 +28,9 @@ public sealed class SignInWithSteamResponse { [JsonProperty(Required = Required.Always)] public Uri ReturnURL { get; private set; } - internal SignInWithSteamResponse(Uri returnURL) => ReturnURL = returnURL ?? throw new ArgumentNullException(nameof(returnURL)); + internal SignInWithSteamResponse(Uri returnURL) { + ArgumentNullException.ThrowIfNull(returnURL); + + ReturnURL = returnURL; + } } diff --git a/ArchiSteamFarm.CustomPlugins.SignInWithSteam/SignInWithSteamController.cs b/ArchiSteamFarm.CustomPlugins.SignInWithSteam/SignInWithSteamController.cs index 58ad5db6b..113cf4bfe 100644 --- a/ArchiSteamFarm.CustomPlugins.SignInWithSteam/SignInWithSteamController.cs +++ b/ArchiSteamFarm.CustomPlugins.SignInWithSteam/SignInWithSteamController.cs @@ -45,10 +45,7 @@ public sealed class SignInWithSteamController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)] public async Task> Post(string botName, [FromBody] SignInWithSteamRequest request) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } - + ArgumentException.ThrowIfNullOrEmpty(botName); ArgumentNullException.ThrowIfNull(request); Bot? bot = Bot.GetBot(botName); diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Backend.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Backend.cs index 00f904aa2..895d065dd 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Backend.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Backend.cs @@ -53,13 +53,8 @@ internal static class Backend { throw new ArgumentNullException(nameof(acceptedMatchableTypes)); } - if (totalInventoryCount == 0) { - throw new ArgumentOutOfRangeException(nameof(totalInventoryCount)); - } - - if (string.IsNullOrEmpty(tradeToken)) { - throw new ArgumentNullException(nameof(tradeToken)); - } + ArgumentOutOfRangeException.ThrowIfZero(totalInventoryCount); + ArgumentException.ThrowIfNullOrEmpty(tradeToken); if (tradeToken.Length != BotConfig.SteamTradeTokenLength) { throw new ArgumentOutOfRangeException(nameof(tradeToken)); @@ -73,10 +68,7 @@ internal static class Backend { } internal static async Task<(HttpStatusCode StatusCode, ImmutableHashSet Users)?> GetListedUsersForMatching(Guid licenseID, Bot bot, WebBrowser webBrowser, IReadOnlyCollection inventory, IReadOnlyCollection acceptedMatchableTypes) { - if (licenseID == Guid.Empty) { - throw new ArgumentOutOfRangeException(nameof(licenseID)); - } - + ArgumentOutOfRangeException.ThrowIfEqual(licenseID, Guid.Empty); ArgumentNullException.ThrowIfNull(bot); ArgumentNullException.ThrowIfNull(webBrowser); diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Commands.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Commands.cs index 4cedd58ce..1c8e99682 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Commands.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Commands.cs @@ -98,9 +98,7 @@ internal static class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); if ((steamID != 0) && !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/AnnouncementRequest.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/AnnouncementRequest.cs index d5592c8df..f62733354 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/AnnouncementRequest.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/AnnouncementRequest.cs @@ -62,17 +62,13 @@ internal sealed class AnnouncementRequest { private readonly string TradeToken; internal AnnouncementRequest(Guid guid, ulong steamID, string tradeToken, IReadOnlyList inventory, IReadOnlyCollection matchableTypes, uint totalInventoryCount, bool matchEverything, byte maxTradeHoldDuration, string? nickname = null, string? avatarHash = null) { - if (guid == Guid.Empty) { - throw new ArgumentOutOfRangeException(nameof(guid)); - } + ArgumentOutOfRangeException.ThrowIfEqual(guid, Guid.Empty); if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(tradeToken)) { - throw new ArgumentNullException(nameof(tradeToken)); - } + ArgumentException.ThrowIfNullOrEmpty(tradeToken); if (tradeToken.Length != BotConfig.SteamTradeTokenLength) { throw new ArgumentOutOfRangeException(nameof(tradeToken)); @@ -86,9 +82,7 @@ internal sealed class AnnouncementRequest { throw new ArgumentNullException(nameof(matchableTypes)); } - if (totalInventoryCount == 0) { - throw new ArgumentOutOfRangeException(nameof(totalInventoryCount)); - } + ArgumentOutOfRangeException.ThrowIfZero(totalInventoryCount); Guid = guid; SteamID = steamID; diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/HeartBeatRequest.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/HeartBeatRequest.cs index e2ba039da..c7223051a 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/HeartBeatRequest.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/HeartBeatRequest.cs @@ -33,9 +33,7 @@ internal sealed class HeartBeatRequest { internal readonly ulong SteamID; internal HeartBeatRequest(Guid guid, ulong steamID) { - if (guid == Guid.Empty) { - throw new ArgumentOutOfRangeException(nameof(guid)); - } + ArgumentOutOfRangeException.ThrowIfEqual(guid, Guid.Empty); if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/InventoriesRequest.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/InventoriesRequest.cs index 3ece72773..baceae0be 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/InventoriesRequest.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/Data/InventoriesRequest.cs @@ -43,9 +43,7 @@ internal sealed class InventoriesRequest { internal readonly ulong SteamID; internal InventoriesRequest(Guid guid, ulong steamID, IReadOnlyCollection inventory, IReadOnlyCollection matchableTypes) { - if (guid == Guid.Empty) { - throw new ArgumentOutOfRangeException(nameof(guid)); - } + ArgumentOutOfRangeException.ThrowIfEqual(guid, Guid.Empty); if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); diff --git a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/ItemsMatcherPlugin.cs b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/ItemsMatcherPlugin.cs index 0e7466199..a19b3700a 100644 --- a/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/ItemsMatcherPlugin.cs +++ b/ArchiSteamFarm.OfficialPlugins.ItemsMatcher/ItemsMatcherPlugin.cs @@ -56,9 +56,7 @@ internal sealed class ItemsMatcherPlugin : OfficialPlugin, IBot, IBotCommand2, I throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if ((args == null) || (args.Length == 0)) { throw new ArgumentNullException(nameof(args)); diff --git a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/Commands.cs b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/Commands.cs index 7da1782c9..4c193ddc4 100644 --- a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/Commands.cs +++ b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/Commands.cs @@ -45,9 +45,7 @@ internal static class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if ((args == null) || (args.Length == 0)) { throw new ArgumentNullException(nameof(args)); @@ -95,10 +93,7 @@ internal static class Commands { } ArgumentNullException.ThrowIfNull(bot); - - if (string.IsNullOrEmpty(activationCode)) { - throw new ArgumentNullException(nameof(activationCode)); - } + ArgumentException.ThrowIfNullOrEmpty(activationCode); if (access < EAccess.Master) { return access > EAccess.None ? bot.Commands.FormatBotResponse(Strings.ErrorAccessDenied) : null; @@ -211,13 +206,8 @@ internal static class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(activationCode)) { - throw new ArgumentNullException(nameof(activationCode)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(activationCode); if ((steamID != 0) && !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); @@ -310,9 +300,7 @@ internal static class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); if ((steamID != 0) && !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); @@ -391,9 +379,7 @@ internal static class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); if ((steamID != 0) && !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); diff --git a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MaFileData.cs b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MaFileData.cs index 0f0d93973..414a7545e 100644 --- a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MaFileData.cs +++ b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MaFileData.cs @@ -61,10 +61,7 @@ internal sealed class MaFileData { internal MaFileData(CTwoFactor_AddAuthenticator_Response data, string deviceID) { ArgumentNullException.ThrowIfNull(data); - - if (string.IsNullOrEmpty(deviceID)) { - throw new ArgumentNullException(nameof(deviceID)); - } + ArgumentException.ThrowIfNullOrEmpty(deviceID); AccountName = data.account_name; DeviceID = deviceID; diff --git a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorHandler.cs b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorHandler.cs index 6343533d3..8a1ce4802 100644 --- a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorHandler.cs +++ b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorHandler.cs @@ -33,9 +33,10 @@ internal sealed class MobileAuthenticatorHandler : ClientMsgHandler { private readonly SteamUnifiedMessages.UnifiedService UnifiedTwoFactorService; internal MobileAuthenticatorHandler(ArchiLogger archiLogger, SteamUnifiedMessages steamUnifiedMessages) { + ArgumentNullException.ThrowIfNull(archiLogger); ArgumentNullException.ThrowIfNull(steamUnifiedMessages); - ArchiLogger = archiLogger ?? throw new ArgumentNullException(nameof(archiLogger)); + ArchiLogger = archiLogger; UnifiedTwoFactorService = steamUnifiedMessages.CreateService(); } @@ -46,9 +47,7 @@ internal sealed class MobileAuthenticatorHandler : ClientMsgHandler { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(deviceID)) { - throw new ArgumentNullException(nameof(deviceID)); - } + ArgumentException.ThrowIfNullOrEmpty(deviceID); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -90,17 +89,9 @@ internal sealed class MobileAuthenticatorHandler : ClientMsgHandler { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(activationCode)) { - throw new ArgumentNullException(nameof(activationCode)); - } - - if (string.IsNullOrEmpty(authenticatorCode)) { - throw new ArgumentNullException(nameof(authenticatorCode)); - } - - if (authenticatorTime <= 0) { - throw new ArgumentOutOfRangeException(nameof(authenticatorTime)); - } + ArgumentException.ThrowIfNullOrEmpty(activationCode); + ArgumentException.ThrowIfNullOrEmpty(authenticatorCode); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(authenticatorTime); if (Client == null) { throw new InvalidOperationException(nameof(Client)); diff --git a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorPlugin.cs b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorPlugin.cs index 6d5cf72ab..6ae154768 100644 --- a/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorPlugin.cs +++ b/ArchiSteamFarm.OfficialPlugins.MobileAuthenticator/MobileAuthenticatorPlugin.cs @@ -51,9 +51,7 @@ internal sealed class MobileAuthenticatorPlugin : OfficialPlugin, IBotCommand2, throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if ((args == null) || (args.Length == 0)) { throw new ArgumentNullException(nameof(args)); diff --git a/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/GlobalCache.cs b/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/GlobalCache.cs index d32849bcd..5134949bf 100644 --- a/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/GlobalCache.cs +++ b/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/GlobalCache.cs @@ -141,10 +141,7 @@ internal sealed class GlobalCache : SerializableFile { } internal void OnPICSChanges(uint currentChangeNumber, IReadOnlyCollection> appChanges) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } - + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); ArgumentNullException.ThrowIfNull(appChanges); if (currentChangeNumber <= LastChangeNumber) { @@ -165,9 +162,7 @@ internal sealed class GlobalCache : SerializableFile { } internal void OnPICSChangesRestart(uint currentChangeNumber) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); if (currentChangeNumber <= LastChangeNumber) { return; @@ -324,9 +319,7 @@ internal sealed class GlobalCache : SerializableFile { } private static bool IsValidDepotKey(string depotKey) { - if (string.IsNullOrEmpty(depotKey)) { - throw new ArgumentNullException(nameof(depotKey)); - } + ArgumentException.ThrowIfNullOrEmpty(depotKey); return (depotKey.Length == 64) && Utilities.IsValidHexadecimalText(depotKey); } diff --git a/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/SteamTokenDumperPlugin.cs b/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/SteamTokenDumperPlugin.cs index 75eed0e09..85a324f34 100644 --- a/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/SteamTokenDumperPlugin.cs +++ b/ArchiSteamFarm.OfficialPlugins.SteamTokenDumper/SteamTokenDumperPlugin.cs @@ -251,10 +251,7 @@ internal sealed class SteamTokenDumperPlugin : OfficialPlugin, IASF, IBot, IBotC } public Task OnPICSChanges(uint currentChangeNumber, IReadOnlyDictionary appChanges, IReadOnlyDictionary packageChanges) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } - + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); ArgumentNullException.ThrowIfNull(appChanges); ArgumentNullException.ThrowIfNull(packageChanges); @@ -272,9 +269,7 @@ internal sealed class SteamTokenDumperPlugin : OfficialPlugin, IASF, IBot, IBotC } public Task OnPICSChangesRestart(uint currentChangeNumber) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); if (Config is not { Enabled: true }) { return Task.CompletedTask; diff --git a/ArchiSteamFarm.Tests/SteamChatMessage.cs b/ArchiSteamFarm.Tests/SteamChatMessage.cs index c43b08ed4..a86bb7692 100644 --- a/ArchiSteamFarm.Tests/SteamChatMessage.cs +++ b/ArchiSteamFarm.Tests/SteamChatMessage.cs @@ -266,7 +266,7 @@ public sealed class SteamChatMessage { return; } - string[] lines = messagePart.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); + string[] lines = messagePart.Split(SharedInfo.NewLineIndicators, StringSplitOptions.None); int bytes = lines.Where(static line => line.Length > 0).Sum(Encoding.UTF8.GetByteCount) + ((lines.Length - 1) * NewlineWeight); diff --git a/ArchiSteamFarm/Collections/ConcurrentEnumerator.cs b/ArchiSteamFarm/Collections/ConcurrentEnumerator.cs index 821047c2b..ff5db328b 100644 --- a/ArchiSteamFarm/Collections/ConcurrentEnumerator.cs +++ b/ArchiSteamFarm/Collections/ConcurrentEnumerator.cs @@ -35,9 +35,10 @@ internal sealed class ConcurrentEnumerator : IEnumerator { internal ConcurrentEnumerator(IReadOnlyCollection collection, IDisposable lockObject) { ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(lockObject); - LockObject = lockObject ?? throw new ArgumentNullException(nameof(lockObject)); Enumerator = collection.GetEnumerator(); + LockObject = lockObject; } public void Dispose() { diff --git a/ArchiSteamFarm/Collections/FixedSizeConcurrentQueue.cs b/ArchiSteamFarm/Collections/FixedSizeConcurrentQueue.cs index 31710e79e..63ab12afb 100644 --- a/ArchiSteamFarm/Collections/FixedSizeConcurrentQueue.cs +++ b/ArchiSteamFarm/Collections/FixedSizeConcurrentQueue.cs @@ -49,9 +49,7 @@ internal sealed class FixedSizeConcurrentQueue : IEnumerable { private byte BackingMaxCount; internal FixedSizeConcurrentQueue(byte maxCount) { - if (maxCount == 0) { - throw new ArgumentNullException(nameof(maxCount)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxCount); MaxCount = maxCount; } diff --git a/ArchiSteamFarm/Core/ASF.cs b/ArchiSteamFarm/Core/ASF.cs index aa3664a70..6d96eb2bf 100644 --- a/ArchiSteamFarm/Core/ASF.cs +++ b/ArchiSteamFarm/Core/ASF.cs @@ -78,7 +78,7 @@ public static class ASF { internal static ICrossProcessSemaphore? RateLimitingSemaphore { get; private set; } internal static ImmutableDictionary? WebLimitingSemaphores { get; private set; } - private static readonly ImmutableHashSet AssembliesNeededBeforeUpdate = ImmutableHashSet.Create("System.IO.Pipes"); + private static readonly ImmutableHashSet AssembliesNeededBeforeUpdate = ImmutableHashSet.Create(StringComparer.Ordinal, "System.IO.Pipes"); private static readonly SemaphoreSlim UpdateSemaphore = new(1, 1); private static Timer? AutoUpdatesTimer; @@ -146,9 +146,7 @@ public static class ASF { } internal static bool IsValidBotName(string botName) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(botName); if (botName[0] == '.') { return false; @@ -386,9 +384,7 @@ public static class ASF { } private static async Task CanHandleWriteEvent(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (LastWriteEvents == null) { throw new InvalidOperationException(nameof(LastWriteEvents)); @@ -515,21 +511,14 @@ public static class ASF { } private static async Task OnChangedConfigFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); await OnCreatedConfigFile(name, fullPath).ConfigureAwait(false); } private static async Task OnChangedConfigFile(string name) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); if (!name.Equals(SharedInfo.IPCConfigFile, StringComparison.OrdinalIgnoreCase) || (GlobalConfig?.IPC != true)) { return; @@ -545,13 +534,8 @@ public static class ASF { } private static async Task OnChangedFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); string extension = Path.GetExtension(name); @@ -569,13 +553,8 @@ public static class ASF { } private static async Task OnChangedKeysFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); await OnCreatedKeysFile(name, fullPath).ConfigureAwait(false); } @@ -618,13 +597,8 @@ public static class ASF { } private static async Task OnCreatedConfigFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); string extension = Path.GetExtension(name); @@ -641,13 +615,8 @@ public static class ASF { } private static async Task OnCreatedFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); string extension = Path.GetExtension(name); @@ -665,13 +634,8 @@ public static class ASF { } private static async Task OnCreatedJsonFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); if (Bot.Bots == null) { throw new InvalidOperationException(nameof(Bot.Bots)); @@ -709,13 +673,8 @@ public static class ASF { } private static async Task OnCreatedKeysFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); if (Bot.Bots == null) { throw new InvalidOperationException(nameof(Bot.Bots)); @@ -754,13 +713,8 @@ public static class ASF { } private static async Task OnDeletedConfigFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); string extension = Path.GetExtension(name); @@ -777,13 +731,8 @@ public static class ASF { } private static async Task OnDeletedFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); string extension = Path.GetExtension(name); @@ -797,13 +746,8 @@ public static class ASF { } private static async Task OnDeletedJsonConfigFile(string name, string fullPath) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (string.IsNullOrEmpty(fullPath)) { - throw new ArgumentNullException(nameof(fullPath)); - } + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(fullPath); if (Bot.Bots == null) { throw new InvalidOperationException(nameof(Bot.Bots)); @@ -872,8 +816,16 @@ public static class ASF { } private static async Task RegisterBots() { - if ((GlobalConfig == null) || (GlobalDatabase == null) || (WebBrowser == null)) { - throw new InvalidOperationException($"{nameof(GlobalConfig)} || {nameof(GlobalDatabase)} || {nameof(WebBrowser)}"); + if (GlobalConfig == null) { + throw new InvalidOperationException(nameof(GlobalConfig)); + } + + if (GlobalDatabase == null) { + throw new InvalidOperationException(nameof(GlobalDatabase)); + } + + if (WebBrowser == null) { + throw new InvalidOperationException(nameof(WebBrowser)); } // Ensure that we ask for a list of servers if we don't have any saved servers available @@ -960,10 +912,7 @@ public static class ASF { private static bool UpdateFromArchive(ZipArchive archive, string targetDirectory) { ArgumentNullException.ThrowIfNull(archive); - - if (string.IsNullOrEmpty(targetDirectory)) { - throw new ArgumentNullException(nameof(targetDirectory)); - } + ArgumentException.ThrowIfNullOrEmpty(targetDirectory); if (SharedInfo.HomeDirectory == AppContext.BaseDirectory) { // We're running a build that includes our dependencies in ASF's home diff --git a/ArchiSteamFarm/Core/AprilFools.cs b/ArchiSteamFarm/Core/AprilFools.cs index 382f79fe7..73fc1e49b 100644 --- a/ArchiSteamFarm/Core/AprilFools.cs +++ b/ArchiSteamFarm/Core/AprilFools.cs @@ -36,7 +36,7 @@ internal static class AprilFools { internal static void Init(object? state = null) { DateTime now = DateTime.Now; - if (now is { Month: 4, Day: 1 }) { + if (now is (_, 4, 1)) { try { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(SharedInfo.LolcatCultureName); } catch (Exception e) { diff --git a/ArchiSteamFarm/Core/ArchiNet.cs b/ArchiSteamFarm/Core/ArchiNet.cs index 4de0fd64c..82358152f 100644 --- a/ArchiSteamFarm/Core/ArchiNet.cs +++ b/ArchiSteamFarm/Core/ArchiNet.cs @@ -44,10 +44,7 @@ internal static class ArchiNet { internal static async Task FetchBuildChecksum(Version version, string variant) { ArgumentNullException.ThrowIfNull(version); - - if (string.IsNullOrEmpty(variant)) { - throw new ArgumentNullException(nameof(variant)); - } + ArgumentException.ThrowIfNullOrEmpty(variant); if (ASF.WebBrowser == null) { throw new InvalidOperationException(nameof(ASF.WebBrowser)); diff --git a/ArchiSteamFarm/Core/OS.cs b/ArchiSteamFarm/Core/OS.cs index f947e08ae..a4d5f2ff2 100644 --- a/ArchiSteamFarm/Core/OS.cs +++ b/ArchiSteamFarm/Core/OS.cs @@ -118,9 +118,7 @@ internal static class OS { } internal static string GetOsResourceName(string objectName) { - if (string.IsNullOrEmpty(objectName)) { - throw new ArgumentNullException(nameof(objectName)); - } + ArgumentException.ThrowIfNullOrEmpty(objectName); return $"{SharedInfo.AssemblyName}-{objectName}"; } @@ -140,7 +138,7 @@ internal static class OS { break; default: - throw new ArgumentOutOfRangeException(nameof(optimizationMode)); + throw new InvalidOperationException(nameof(optimizationMode)); } } diff --git a/ArchiSteamFarm/Core/Utilities.cs b/ArchiSteamFarm/Core/Utilities.cs index 8f8725112..e0d84d4a4 100644 --- a/ArchiSteamFarm/Core/Utilities.cs +++ b/ArchiSteamFarm/Core/Utilities.cs @@ -59,18 +59,14 @@ public static class Utilities { throw new InvalidOperationException($"{nameof(args.Length)} && {nameof(argsToSkip)}"); } - if (string.IsNullOrEmpty(delimiter)) { - throw new ArgumentNullException(nameof(delimiter)); - } + ArgumentException.ThrowIfNullOrEmpty(delimiter); return string.Join(delimiter, args.Skip(argsToSkip)); } [PublicAPI] public static string GetArgsAsText(string text, byte argsToSkip) { - if (string.IsNullOrEmpty(text)) { - throw new ArgumentNullException(nameof(text)); - } + ArgumentException.ThrowIfNullOrEmpty(text); string[] args = text.Split(Array.Empty(), argsToSkip + 1, StringSplitOptions.RemoveEmptyEntries); @@ -81,10 +77,7 @@ public static class Utilities { public static string? GetCookieValue(this CookieContainer cookieContainer, Uri uri, string name) { ArgumentNullException.ThrowIfNull(cookieContainer); ArgumentNullException.ThrowIfNull(uri); - - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); CookieCollection cookies = cookieContainer.GetCookies(uri); @@ -122,24 +115,18 @@ public static class Utilities { public static async Task> InParallel(IEnumerable> tasks) { ArgumentNullException.ThrowIfNull(tasks); - IList results; - switch (ASF.GlobalConfig?.OptimizationMode) { case GlobalConfig.EOptimizationMode.MinMemoryUsage: - results = new List(); + List results = new(); foreach (Task task in tasks) { results.Add(await task.ConfigureAwait(false)); } - break; + return results; default: - results = await Task.WhenAll(tasks).ConfigureAwait(false); - - break; + return await Task.WhenAll(tasks).ConfigureAwait(false); } - - return results; } [PublicAPI] @@ -174,27 +161,21 @@ public static class Utilities { [PublicAPI] public static bool IsValidCdKey(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); return GeneratedRegexes.CdKey().IsMatch(key); } [PublicAPI] public static bool IsValidHexadecimalText(string text) { - if (string.IsNullOrEmpty(text)) { - throw new ArgumentNullException(nameof(text)); - } + ArgumentException.ThrowIfNullOrEmpty(text); return (text.Length % 2 == 0) && text.All(Uri.IsHexDigit); } [PublicAPI] public static JwtSecurityToken? ReadJwtToken(string token) { - if (string.IsNullOrEmpty(token)) { - throw new ArgumentNullException(nameof(token)); - } + ArgumentException.ThrowIfNullOrEmpty(token); try { return JwtSecurityTokenHandler.ReadJwtToken(token); @@ -274,9 +255,7 @@ public static class Utilities { } internal static void DeleteEmptyDirectoriesRecursively(string directory) { - if (string.IsNullOrEmpty(directory)) { - throw new ArgumentNullException(nameof(directory)); - } + ArgumentException.ThrowIfNullOrEmpty(directory); if (!Directory.Exists(directory)) { return; @@ -304,9 +283,7 @@ public static class Utilities { } internal static bool RelativeDirectoryStartsWith(string directory, params string[] prefixes) { - if (string.IsNullOrEmpty(directory)) { - throw new ArgumentNullException(nameof(directory)); - } + ArgumentException.ThrowIfNullOrEmpty(directory); #pragma warning disable CA1508 // False positive, params could be null when explicitly set if ((prefixes == null) || (prefixes.Length == 0)) { @@ -318,9 +295,7 @@ public static class Utilities { } internal static (bool IsWeak, string? Reason) TestPasswordStrength(string password, ISet? additionallyForbiddenPhrases = null) { - if (string.IsNullOrEmpty(password)) { - throw new ArgumentNullException(nameof(password)); - } + ArgumentException.ThrowIfNullOrEmpty(password); HashSet forbiddenPhrases = ForbiddenPasswordPhrases.ToHashSet(StringComparer.InvariantCultureIgnoreCase); diff --git a/ArchiSteamFarm/Helpers/ArchiCacheable.cs b/ArchiSteamFarm/Helpers/ArchiCacheable.cs index 36faa462d..ffd2f112c 100644 --- a/ArchiSteamFarm/Helpers/ArchiCacheable.cs +++ b/ArchiSteamFarm/Helpers/ArchiCacheable.cs @@ -40,7 +40,9 @@ public sealed class ArchiCacheable : IDisposable { private T? InitializedValue; public ArchiCacheable(Func> resolveFunction, TimeSpan? cacheLifetime = null) { - ResolveFunction = resolveFunction ?? throw new ArgumentNullException(nameof(resolveFunction)); + ArgumentNullException.ThrowIfNull(resolveFunction); + + ResolveFunction = resolveFunction; CacheLifetime = cacheLifetime ?? Timeout.InfiniteTimeSpan; } diff --git a/ArchiSteamFarm/Helpers/ArchiCryptoHelper.cs b/ArchiSteamFarm/Helpers/ArchiCryptoHelper.cs index 129aad3f7..889fa26cf 100644 --- a/ArchiSteamFarm/Helpers/ArchiCryptoHelper.cs +++ b/ArchiSteamFarm/Helpers/ArchiCryptoHelper.cs @@ -64,9 +64,7 @@ public static class ArchiCryptoHelper { throw new InvalidEnumArgumentException(nameof(cryptoMethod), (int) cryptoMethod, typeof(ECryptoMethod)); } - if (string.IsNullOrEmpty(encryptedString)) { - throw new ArgumentNullException(nameof(encryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(encryptedString); return cryptoMethod switch { ECryptoMethod.AES => DecryptAES(encryptedString), @@ -74,7 +72,7 @@ public static class ArchiCryptoHelper { ECryptoMethod.File => await ReadFromFile(encryptedString).ConfigureAwait(false), ECryptoMethod.PlainText => encryptedString, ECryptoMethod.ProtectedDataForCurrentUser => DecryptProtectedDataForCurrentUser(encryptedString), - _ => throw new ArgumentOutOfRangeException(nameof(cryptoMethod)) + _ => throw new InvalidOperationException(nameof(cryptoMethod)) }; } @@ -83,9 +81,7 @@ public static class ArchiCryptoHelper { throw new InvalidEnumArgumentException(nameof(cryptoMethod), (int) cryptoMethod, typeof(ECryptoMethod)); } - if (string.IsNullOrEmpty(decryptedString)) { - throw new ArgumentNullException(nameof(decryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(decryptedString); return cryptoMethod switch { ECryptoMethod.AES => EncryptAES(decryptedString), @@ -93,7 +89,7 @@ public static class ArchiCryptoHelper { ECryptoMethod.File => decryptedString, ECryptoMethod.PlainText => decryptedString, ECryptoMethod.ProtectedDataForCurrentUser => EncryptProtectedDataForCurrentUser(decryptedString), - _ => throw new ArgumentOutOfRangeException(nameof(cryptoMethod)) + _ => throw new InvalidOperationException(nameof(cryptoMethod)) }; } @@ -102,9 +98,7 @@ public static class ArchiCryptoHelper { throw new InvalidEnumArgumentException(nameof(hashingMethod), (int) hashingMethod, typeof(EHashingMethod)); } - if (string.IsNullOrEmpty(stringToHash)) { - throw new ArgumentNullException(nameof(stringToHash)); - } + ArgumentException.ThrowIfNullOrEmpty(stringToHash); if (hashingMethod == EHashingMethod.PlainText) { return stringToHash; @@ -125,9 +119,7 @@ public static class ArchiCryptoHelper { throw new ArgumentNullException(nameof(salt)); } - if (hashLength == 0) { - throw new ArgumentOutOfRangeException(nameof(hashLength)); - } + ArgumentOutOfRangeException.ThrowIfZero(hashLength); if (!Enum.IsDefined(hashingMethod)) { throw new InvalidEnumArgumentException(nameof(hashingMethod), (int) hashingMethod, typeof(EHashingMethod)); @@ -143,7 +135,7 @@ public static class ArchiCryptoHelper { return Pbkdf2.ComputeDerivedKey(hashAlgorithm, salt, SteamParentalPbkdf2Iterations, hashLength); } default: - throw new ArgumentOutOfRangeException(nameof(hashingMethod)); + throw new InvalidOperationException(nameof(hashingMethod)); } } @@ -177,9 +169,7 @@ public static class ArchiCryptoHelper { } internal static void SetEncryptionKey(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); if (!HasDefaultCryptKey) { ASF.ArchiLogger.LogGenericError(Strings.ErrorAborted); @@ -208,9 +198,7 @@ public static class ArchiCryptoHelper { } private static string? DecryptAES(string encryptedString) { - if (string.IsNullOrEmpty(encryptedString)) { - throw new ArgumentNullException(nameof(encryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(encryptedString); try { byte[] key = SHA256.HashData(EncryptionKey); @@ -227,9 +215,7 @@ public static class ArchiCryptoHelper { } private static string? DecryptProtectedDataForCurrentUser(string encryptedString) { - if (string.IsNullOrEmpty(encryptedString)) { - throw new ArgumentNullException(nameof(encryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(encryptedString); if (!OperatingSystem.IsWindows()) { return null; @@ -251,9 +237,7 @@ public static class ArchiCryptoHelper { } private static string? EncryptAES(string decryptedString) { - if (string.IsNullOrEmpty(decryptedString)) { - throw new ArgumentNullException(nameof(decryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(decryptedString); try { byte[] key = SHA256.HashData(EncryptionKey); @@ -270,9 +254,7 @@ public static class ArchiCryptoHelper { } private static string? EncryptProtectedDataForCurrentUser(string decryptedString) { - if (string.IsNullOrEmpty(decryptedString)) { - throw new ArgumentNullException(nameof(decryptedString)); - } + ArgumentException.ThrowIfNullOrEmpty(decryptedString); if (!OperatingSystem.IsWindows()) { return null; @@ -294,9 +276,7 @@ public static class ArchiCryptoHelper { } private static async Task ReadFromFile(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { return null; diff --git a/ArchiSteamFarm/Helpers/CrossProcessFileBasedSemaphore.cs b/ArchiSteamFarm/Helpers/CrossProcessFileBasedSemaphore.cs index fec706bd0..a39fccbe0 100644 --- a/ArchiSteamFarm/Helpers/CrossProcessFileBasedSemaphore.cs +++ b/ArchiSteamFarm/Helpers/CrossProcessFileBasedSemaphore.cs @@ -38,9 +38,7 @@ internal sealed class CrossProcessFileBasedSemaphore : IAsyncDisposable, ICrossP private FileStream? FileLock; internal CrossProcessFileBasedSemaphore(string name) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); FilePath = Path.Combine(Path.GetTempPath(), SharedInfo.ASF, name); diff --git a/ArchiSteamFarm/Helpers/SemaphoreLock.cs b/ArchiSteamFarm/Helpers/SemaphoreLock.cs index e59d9a42c..a2d275589 100644 --- a/ArchiSteamFarm/Helpers/SemaphoreLock.cs +++ b/ArchiSteamFarm/Helpers/SemaphoreLock.cs @@ -27,7 +27,11 @@ namespace ArchiSteamFarm.Helpers; internal sealed class SemaphoreLock : IDisposable { private readonly SemaphoreSlim Semaphore; - internal SemaphoreLock(SemaphoreSlim semaphore) => Semaphore = semaphore ?? throw new ArgumentNullException(nameof(semaphore)); + internal SemaphoreLock(SemaphoreSlim semaphore) { + ArgumentNullException.ThrowIfNull(semaphore); + + Semaphore = semaphore; + } public void Dispose() => Semaphore.Release(); } diff --git a/ArchiSteamFarm/Helpers/SerializableFile.cs b/ArchiSteamFarm/Helpers/SerializableFile.cs index 85793bdc6..bde253596 100644 --- a/ArchiSteamFarm/Helpers/SerializableFile.cs +++ b/ArchiSteamFarm/Helpers/SerializableFile.cs @@ -81,10 +81,6 @@ public abstract class SerializableFile : IDisposable { string json = JsonConvert.SerializeObject(this, Debugging.IsUserDebugging ? Formatting.Indented : Formatting.None); - if (string.IsNullOrEmpty(json)) { - throw new InvalidOperationException(nameof(json)); - } - // We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist string newFilePath = $"{FilePath}.new"; @@ -129,13 +125,8 @@ public abstract class SerializableFile : IDisposable { } internal static async Task Write(string filePath, string json) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } - - if (string.IsNullOrEmpty(json)) { - throw new ArgumentNullException(nameof(json)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); + ArgumentException.ThrowIfNullOrEmpty(json); string newFilePath = $"{filePath}.new"; diff --git a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs index 10c31be39..2a1bacc6e 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/BotController.cs @@ -47,9 +47,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> BotDelete(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -69,9 +67,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public ActionResult BotGet(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -90,10 +86,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> BotPost(string botNames, [FromBody] BotRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); if (Bot.Bots == null) { @@ -108,7 +101,7 @@ public sealed class BotController : ArchiController { request.BotConfig.Saving = true; - HashSet bots = botNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToHashSet(Bot.BotsComparer); + HashSet bots = botNames.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries).ToHashSet(Bot.BotsComparer); if (bots.Any(static botName => !ASF.IsValidBotName(botName))) { return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(botNames)))); @@ -165,9 +158,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> GamesToRedeemInBackgroundDelete(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -187,9 +178,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> GamesToRedeemInBackgroundGet(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -217,10 +206,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> GamesToRedeemInBackgroundPost(string botNames, [FromBody] BotGamesToRedeemInBackgroundRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); if (request.GamesToRedeemInBackground.Count == 0) { @@ -258,10 +244,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> InputPost(string botNames, [FromBody] BotInputRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); if ((request.Type == ASF.EUserInputType.None) || !Enum.IsDefined(request.Type) || string.IsNullOrEmpty(request.Value)) { @@ -287,10 +270,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> PausePost(string botNames, [FromBody] BotPauseRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); HashSet? bots = Bot.GetBots(botNames); @@ -316,10 +296,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse>>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> RedeemPost(string botNames, [FromBody] BotRedeemRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); if (request.KeysToRedeem.Count == 0) { @@ -358,10 +335,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> RenamePost(string botName, [FromBody] BotRenameRequest request) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } - + ArgumentException.ThrowIfNullOrEmpty(botName); ArgumentNullException.ThrowIfNull(request); if (Bot.Bots == null) { @@ -388,9 +362,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> ResumePost(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -410,9 +382,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> StartPost(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -432,9 +402,7 @@ public sealed class BotController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> StopPost(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/GitHubController.cs b/ArchiSteamFarm/IPC/Controllers/Api/GitHubController.cs index f78632cc3..1fa92ebd9 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/GitHubController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/GitHubController.cs @@ -60,9 +60,7 @@ public sealed class GitHubController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)] public async Task> GitHubReleaseGet(string version) { - if (string.IsNullOrEmpty(version)) { - throw new ArgumentNullException(nameof(version)); - } + ArgumentException.ThrowIfNullOrEmpty(version); GitHub.ReleaseResponse? releaseResponse; @@ -95,9 +93,7 @@ public sealed class GitHubController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)] public async Task> GitHubWikiHistoryGet(string page) { - if (string.IsNullOrEmpty(page)) { - throw new ArgumentNullException(nameof(page)); - } + ArgumentException.ThrowIfNullOrEmpty(page); Dictionary? revisions = await GitHub.GetWikiHistory(page).ConfigureAwait(false); @@ -116,9 +112,7 @@ public sealed class GitHubController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.ServiceUnavailable)] public async Task> GitHubWikiPageGet(string page, [FromQuery] string? revision = null) { - if (string.IsNullOrEmpty(page)) { - throw new ArgumentNullException(nameof(page)); - } + ArgumentException.ThrowIfNullOrEmpty(page); string? html = await GitHub.GetWikiPage(page, revision).ConfigureAwait(false); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/IPCBansController.cs b/ArchiSteamFarm/IPC/Controllers/Api/IPCBansController.cs index 436af95f3..35b923a31 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/IPCBansController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/IPCBansController.cs @@ -51,9 +51,7 @@ public sealed class IPCBansController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public ActionResult DeleteSpecific(string ipAddress) { - if (string.IsNullOrEmpty(ipAddress)) { - throw new ArgumentNullException(nameof(ipAddress)); - } + ArgumentException.ThrowIfNullOrEmpty(ipAddress); if (!IPAddress.TryParse(ipAddress, out IPAddress? remoteAddress)) { return BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(ipAddress)))); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs b/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs index efc1b3e22..59d3ccce4 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs @@ -163,11 +163,7 @@ public sealed class NLogController : ArchiController { private static async Task PostLoggedJsonUpdate(WebSocket webSocket, string json, SemaphoreSlim sendSemaphore, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(webSocket); - - if (string.IsNullOrEmpty(json)) { - throw new ArgumentNullException(nameof(json)); - } - + ArgumentException.ThrowIfNullOrEmpty(json); ArgumentNullException.ThrowIfNull(sendSemaphore); if (cancellationToken.IsCancellationRequested || (webSocket.State != WebSocketState.Open)) { @@ -203,11 +199,7 @@ public sealed class NLogController : ArchiController { private static async Task PostLoggedMessageUpdate(WebSocket webSocket, string loggedMessage, SemaphoreSlim sendSemaphore, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(webSocket); - - if (string.IsNullOrEmpty(loggedMessage)) { - throw new ArgumentNullException(nameof(loggedMessage)); - } - + ArgumentException.ThrowIfNullOrEmpty(loggedMessage); ArgumentNullException.ThrowIfNull(sendSemaphore); if (cancellationToken.IsCancellationRequested || (webSocket.State != WebSocketState.Open)) { diff --git a/ArchiSteamFarm/IPC/Controllers/Api/StorageController.cs b/ArchiSteamFarm/IPC/Controllers/Api/StorageController.cs index f1670925c..38e2f1a99 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/StorageController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/StorageController.cs @@ -36,9 +36,7 @@ public sealed class StorageController : ArchiController { [HttpDelete] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] public ActionResult StorageDelete(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); if (ASF.GlobalDatabase == null) { throw new InvalidOperationException(nameof(ASF.GlobalDatabase)); @@ -55,9 +53,7 @@ public sealed class StorageController : ArchiController { [HttpGet] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] public ActionResult StorageGet(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); if (ASF.GlobalDatabase == null) { throw new InvalidOperationException(nameof(ASF.GlobalDatabase)); @@ -75,10 +71,7 @@ public sealed class StorageController : ArchiController { [HttpPost] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] public ActionResult StoragePost(string key, [FromBody] JToken value) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } - + ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(value); if (ASF.GlobalDatabase == null) { diff --git a/ArchiSteamFarm/IPC/Controllers/Api/StructureController.cs b/ArchiSteamFarm/IPC/Controllers/Api/StructureController.cs index 26e2e9be6..3163b5165 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/StructureController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/StructureController.cs @@ -40,9 +40,7 @@ public sealed class StructureController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public ActionResult StructureGet(string structure) { - if (string.IsNullOrEmpty(structure)) { - throw new ArgumentNullException(nameof(structure)); - } + ArgumentException.ThrowIfNullOrEmpty(structure); Type? targetType = WebUtilities.ParseType(structure); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs b/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs index 008a733cd..c2f659490 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/TwoFactorAuthenticationController.cs @@ -45,9 +45,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController { [ProducesResponseType(typeof(GenericResponse>>>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> ConfirmationsGet(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -75,10 +73,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController { [ProducesResponseType(typeof(GenericResponse>>>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> ConfirmationsPost(string botNames, [FromBody] TwoFactorAuthenticationConfirmationsRequest request) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(request); if (request.AcceptedType.HasValue && ((request.AcceptedType.Value == Confirmation.EConfirmationType.Unknown) || !Enum.IsDefined(request.AcceptedType.Value))) { @@ -110,9 +105,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController { [ProducesResponseType(typeof(GenericResponse>>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> Delete(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -140,10 +133,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController { [ProducesResponseType(typeof(GenericResponse>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> Post(string botNames, [FromBody] MobileAuthenticator authenticator) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - + ArgumentException.ThrowIfNullOrEmpty(botNames); ArgumentNullException.ThrowIfNull(authenticator); HashSet? bots = Bot.GetBots(botNames); @@ -171,9 +161,7 @@ public sealed class TwoFactorAuthenticationController : ArchiController { [ProducesResponseType(typeof(GenericResponse>>), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public async Task> TokenGet(string botNames) { - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); diff --git a/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs b/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs index 7d8e072dd..942d847c5 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/TypeController.cs @@ -45,9 +45,7 @@ public sealed class TypeController : ArchiController { [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(GenericResponse), (int) HttpStatusCode.BadRequest)] public ActionResult TypeGet(string type) { - if (string.IsNullOrEmpty(type)) { - throw new ArgumentNullException(nameof(type)); - } + ArgumentException.ThrowIfNullOrEmpty(type); Type? targetType = WebUtilities.ParseType(type); diff --git a/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs b/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs index e5f2b82e3..5f242eab1 100644 --- a/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs +++ b/ArchiSteamFarm/IPC/Integration/ApiAuthenticationMiddleware.cs @@ -58,10 +58,11 @@ internal sealed class ApiAuthenticationMiddleware { private readonly RequestDelegate Next; public ApiAuthenticationMiddleware(RequestDelegate next, IOptions forwardedHeadersOptions) { - Next = next ?? throw new ArgumentNullException(nameof(next)); - + ArgumentNullException.ThrowIfNull(next); ArgumentNullException.ThrowIfNull(forwardedHeadersOptions); + Next = next; + ForwardedHeadersOptions = forwardedHeadersOptions.Value ?? throw new InvalidOperationException(nameof(forwardedHeadersOptions)); lock (FailedAuthorizations) { diff --git a/ArchiSteamFarm/IPC/Requests/CommandRequest.cs b/ArchiSteamFarm/IPC/Requests/CommandRequest.cs index 00b9ff9ea..af3fb9f2c 100644 --- a/ArchiSteamFarm/IPC/Requests/CommandRequest.cs +++ b/ArchiSteamFarm/IPC/Requests/CommandRequest.cs @@ -36,9 +36,7 @@ public sealed class CommandRequest { public string Command { get; private set; } = ""; internal CommandRequest(string command) { - if (string.IsNullOrEmpty(command)) { - throw new ArgumentNullException(nameof(command)); - } + ArgumentException.ThrowIfNullOrEmpty(command); Command = command; } diff --git a/ArchiSteamFarm/IPC/Requests/TwoFactorAuthenticationConfirmationsRequest.cs b/ArchiSteamFarm/IPC/Requests/TwoFactorAuthenticationConfirmationsRequest.cs index 6986957ff..415d6d517 100644 --- a/ArchiSteamFarm/IPC/Requests/TwoFactorAuthenticationConfirmationsRequest.cs +++ b/ArchiSteamFarm/IPC/Requests/TwoFactorAuthenticationConfirmationsRequest.cs @@ -57,7 +57,7 @@ public sealed class TwoFactorAuthenticationConfirmationsRequest { /// [JsonProperty($"{SharedInfo.UlongCompatibilityStringPrefix}{nameof(AcceptedCreatorIDs)}", Required = Required.DisallowNull)] public ImmutableHashSet SAcceptedCreatorIDs { - get => AcceptedCreatorIDs.Select(static creatorID => creatorID.ToString(CultureInfo.InvariantCulture)).ToImmutableHashSet(); + get => AcceptedCreatorIDs.Select(static creatorID => creatorID.ToString(CultureInfo.InvariantCulture)).ToImmutableHashSet(StringComparer.Ordinal); set { ArgumentNullException.ThrowIfNull(value); diff --git a/ArchiSteamFarm/IPC/Responses/ASFResponse.cs b/ArchiSteamFarm/IPC/Responses/ASFResponse.cs index 1f6af92e1..99f7e4d69 100644 --- a/ArchiSteamFarm/IPC/Responses/ASFResponse.cs +++ b/ArchiSteamFarm/IPC/Responses/ASFResponse.cs @@ -77,12 +77,22 @@ public sealed class ASFResponse { public Version Version { get; private set; } internal ASFResponse(string buildVariant, bool canUpdate, GlobalConfig globalConfig, uint memoryUsage, DateTime processStartTime, Version version) { - BuildVariant = !string.IsNullOrEmpty(buildVariant) ? buildVariant : throw new ArgumentNullException(nameof(buildVariant)); + ArgumentException.ThrowIfNullOrEmpty(buildVariant); + ArgumentNullException.ThrowIfNull(globalConfig); + ArgumentOutOfRangeException.ThrowIfZero(memoryUsage); + + // TODO: Use this instead once we get rid of generic-netf + //ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(processStartTime, DateTime.UnixEpoch); + ArgumentOutOfRangeException.ThrowIfEqual(processStartTime, DateTime.MinValue); + + ArgumentNullException.ThrowIfNull(version); + + BuildVariant = buildVariant; CanUpdate = canUpdate; - GlobalConfig = globalConfig ?? throw new ArgumentNullException(nameof(globalConfig)); - MemoryUsage = memoryUsage > 0 ? memoryUsage : throw new ArgumentOutOfRangeException(nameof(memoryUsage)); - ProcessStartTime = processStartTime > DateTime.MinValue ? processStartTime : throw new ArgumentOutOfRangeException(nameof(processStartTime)); - Version = version ?? throw new ArgumentNullException(nameof(version)); + GlobalConfig = globalConfig; + MemoryUsage = memoryUsage; + ProcessStartTime = processStartTime; + Version = version; Service = Program.Service; } diff --git a/ArchiSteamFarm/IPC/Responses/LogResponse.cs b/ArchiSteamFarm/IPC/Responses/LogResponse.cs index b53d08907..02cd685ea 100644 --- a/ArchiSteamFarm/IPC/Responses/LogResponse.cs +++ b/ArchiSteamFarm/IPC/Responses/LogResponse.cs @@ -42,11 +42,10 @@ public sealed class LogResponse { public int TotalLines { get; private set; } internal LogResponse(int totalLines, IReadOnlyList content) { - if (totalLines < 0) { - throw new ArgumentOutOfRangeException(nameof(totalLines)); - } + ArgumentOutOfRangeException.ThrowIfNegative(totalLines); + ArgumentNullException.ThrowIfNull(content); TotalLines = totalLines; - Content = content ?? throw new ArgumentNullException(nameof(content)); + Content = content; } } diff --git a/ArchiSteamFarm/IPC/Responses/TypeResponse.cs b/ArchiSteamFarm/IPC/Responses/TypeResponse.cs index b261884a5..d5ba94a0e 100644 --- a/ArchiSteamFarm/IPC/Responses/TypeResponse.cs +++ b/ArchiSteamFarm/IPC/Responses/TypeResponse.cs @@ -47,7 +47,10 @@ public sealed class TypeResponse { public TypeProperties Properties { get; private set; } internal TypeResponse(Dictionary body, TypeProperties properties) { - Body = body ?? throw new ArgumentNullException(nameof(body)); - Properties = properties ?? throw new ArgumentNullException(nameof(properties)); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(properties); + + Body = body; + Properties = properties; } } diff --git a/ArchiSteamFarm/IPC/Startup.cs b/ArchiSteamFarm/IPC/Startup.cs index 322c04e92..041aa5519 100644 --- a/ArchiSteamFarm/IPC/Startup.cs +++ b/ArchiSteamFarm/IPC/Startup.cs @@ -53,13 +53,18 @@ using Microsoft.Net.Http.Headers; using Microsoft.OpenApi.Models; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; +using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork; namespace ArchiSteamFarm.IPC; internal sealed class Startup { private readonly IConfiguration Configuration; - public Startup(IConfiguration configuration) => Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + public Startup(IConfiguration configuration) { + ArgumentNullException.ThrowIfNull(configuration); + + Configuration = configuration; + } [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "PathString is a primitive, it's unlikely to be trimmed to the best of our knowledge")] [UsedImplicitly] diff --git a/ArchiSteamFarm/IPC/WebUtilities.cs b/ArchiSteamFarm/IPC/WebUtilities.cs index 1c9e57d05..406dbed9f 100644 --- a/ArchiSteamFarm/IPC/WebUtilities.cs +++ b/ArchiSteamFarm/IPC/WebUtilities.cs @@ -63,9 +63,7 @@ internal static class WebUtilities { [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "We don't care about trimmed assemblies, as we need it to work only with the known (used) ones")] internal static Type? ParseType(string typeText) { - if (string.IsNullOrEmpty(typeText)) { - throw new ArgumentNullException(nameof(typeText)); - } + ArgumentException.ThrowIfNullOrEmpty(typeText); Type? targetType = Type.GetType(typeText); diff --git a/ArchiSteamFarm/NLog/ArchiLogger.cs b/ArchiSteamFarm/NLog/ArchiLogger.cs index d0e3a5e15..c6dee53cd 100644 --- a/ArchiSteamFarm/NLog/ArchiLogger.cs +++ b/ArchiSteamFarm/NLog/ArchiLogger.cs @@ -37,22 +37,15 @@ public sealed class ArchiLogger { private readonly Logger Logger; public ArchiLogger(string name) { - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); Logger = LogManager.GetLogger(name); } [PublicAPI] public void LogGenericDebug(string message, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Debug($"{previousMethodName}() {message}"); } @@ -60,10 +53,7 @@ public sealed class ArchiLogger { [PublicAPI] public void LogGenericDebuggingException(Exception exception, [CallerMemberName] string? previousMethodName = null) { ArgumentNullException.ThrowIfNull(exception); - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); if (!Debugging.IsUserDebugging) { return; @@ -74,13 +64,8 @@ public sealed class ArchiLogger { [PublicAPI] public void LogGenericError(string message, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Error($"{previousMethodName}() {message}"); } @@ -88,49 +73,31 @@ public sealed class ArchiLogger { [PublicAPI] public void LogGenericException(Exception exception, [CallerMemberName] string? previousMethodName = null) { ArgumentNullException.ThrowIfNull(exception); - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Error(exception, $"{previousMethodName}()"); } [PublicAPI] public void LogGenericInfo(string message, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Info($"{previousMethodName}() {message}"); } [PublicAPI] public void LogGenericTrace(string message, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Trace($"{previousMethodName}() {message}"); } [PublicAPI] public void LogGenericWarning(string message, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Warn($"{previousMethodName}() {message}"); } @@ -138,35 +105,22 @@ public sealed class ArchiLogger { [PublicAPI] public void LogGenericWarningException(Exception exception, [CallerMemberName] string? previousMethodName = null) { ArgumentNullException.ThrowIfNull(exception); - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Warn(exception, $"{previousMethodName}()"); } [PublicAPI] - public void LogNullError(object? nullObject, [CallerArgumentExpression("nullObject")] string? nullObjectName = null, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(nullObjectName)) { - throw new ArgumentNullException(nameof(nullObjectName)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + public void LogNullError(object? nullObject, [CallerArgumentExpression(nameof(nullObject))] string? nullObjectName = null, [CallerMemberName] string? previousMethodName = null) { + ArgumentException.ThrowIfNullOrEmpty(nullObjectName); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.ErrorObjectIsNull, nullObjectName), previousMethodName); } internal void LogChatMessage(bool echo, string message, ulong chatGroupID = 0, ulong chatID = 0, ulong steamID = 0, [CallerMemberName] string? previousMethodName = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(message); + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); if (((chatGroupID == 0) || (chatID == 0)) && (steamID == 0)) { throw new InvalidOperationException($"(({nameof(chatGroupID)} || {nameof(chatID)}) && {nameof(steamID)})"); @@ -199,10 +153,7 @@ public sealed class ArchiLogger { internal async Task LogFatalException(Exception exception, [CallerMemberName] string? previousMethodName = null) { ArgumentNullException.ThrowIfNull(exception); - - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); Logger.Fatal(exception, $"{previousMethodName}()"); @@ -256,9 +207,7 @@ public sealed class ArchiLogger { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(previousMethodName)) { - throw new ArgumentNullException(nameof(previousMethodName)); - } + ArgumentException.ThrowIfNullOrEmpty(previousMethodName); ulong steamID64 = steamID; diff --git a/ArchiSteamFarm/NLog/Logging.cs b/ArchiSteamFarm/NLog/Logging.cs index d8c79fd3b..89495e723 100644 --- a/ArchiSteamFarm/NLog/Logging.cs +++ b/ArchiSteamFarm/NLog/Logging.cs @@ -79,9 +79,7 @@ internal static class Logging { throw new InvalidEnumArgumentException(nameof(userInputType), (int) userInputType, typeof(ASF.EUserInputType)); } - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(botName); if (Program.Service || (ASF.GlobalConfig?.Headless ?? GlobalConfig.DefaultHeadless)) { ASF.ArchiLogger.LogGenericWarning(Strings.ErrorUserInputRunningInHeadlessMode); @@ -275,9 +273,7 @@ internal static class Logging { } private static async Task BeepUntilCanceled(CancellationToken cancellationToken, byte secondsDelay = 30) { - if (secondsDelay == 0) { - throw new ArgumentOutOfRangeException(nameof(secondsDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(secondsDelay); while (!cancellationToken.IsCancellationRequested) { try { diff --git a/ArchiSteamFarm/NLog/Targets/HistoryTarget.cs b/ArchiSteamFarm/NLog/Targets/HistoryTarget.cs index 31ceafa26..b89babcb0 100644 --- a/ArchiSteamFarm/NLog/Targets/HistoryTarget.cs +++ b/ArchiSteamFarm/NLog/Targets/HistoryTarget.cs @@ -78,6 +78,10 @@ internal sealed class HistoryTarget : TargetWithLayout { internal sealed class NewHistoryEntryArgs : EventArgs { internal readonly string Message; - internal NewHistoryEntryArgs(string message) => Message = message ?? throw new ArgumentNullException(nameof(message)); + internal NewHistoryEntryArgs(string message) { + ArgumentNullException.ThrowIfNull(message); + + Message = message; + } } } diff --git a/ArchiSteamFarm/NLog/Targets/SteamTarget.cs b/ArchiSteamFarm/NLog/Targets/SteamTarget.cs index 0a9811cdd..42d259bb4 100644 --- a/ArchiSteamFarm/NLog/Targets/SteamTarget.cs +++ b/ArchiSteamFarm/NLog/Targets/SteamTarget.cs @@ -100,9 +100,7 @@ internal sealed class SteamTarget : AsyncTaskTarget { } private async Task SendGroupMessage(string message, Bot? bot = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if (bot == null) { bot = Bot.Bots?.Values.FirstOrDefault(static targetBot => targetBot.IsConnectedAndLoggedOn); @@ -118,9 +116,7 @@ internal sealed class SteamTarget : AsyncTaskTarget { } private async Task SendPrivateMessage(string message, Bot? bot = null) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if (bot == null) { bot = Bot.Bots?.Values.FirstOrDefault(targetBot => targetBot.IsConnectedAndLoggedOn && (targetBot.SteamID != SteamID)); diff --git a/ArchiSteamFarm/Plugins/PluginsCore.cs b/ArchiSteamFarm/Plugins/PluginsCore.cs index f45e8639c..20aac09de 100644 --- a/ArchiSteamFarm/Plugins/PluginsCore.cs +++ b/ArchiSteamFarm/Plugins/PluginsCore.cs @@ -56,9 +56,7 @@ public static class PluginsCore { [PublicAPI] public static async Task GetCrossProcessSemaphore(string objectName) { - if (string.IsNullOrEmpty(objectName)) { - throw new ArgumentNullException(nameof(objectName)); - } + ArgumentException.ThrowIfNullOrEmpty(objectName); if (ASF.GlobalConfig == null) { throw new InvalidOperationException(nameof(ASF.GlobalConfig)); @@ -294,9 +292,7 @@ public static class PluginsCore { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if ((args == null) || (args.Length == 0)) { throw new ArgumentNullException(nameof(args)); @@ -462,9 +458,7 @@ public static class PluginsCore { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if ((ActivePlugins == null) || (ActivePlugins.Count == 0)) { return null; @@ -576,10 +570,7 @@ public static class PluginsCore { } internal static async Task OnPICSChanges(uint currentChangeNumber, IReadOnlyDictionary appChanges, IReadOnlyDictionary packageChanges) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } - + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); ArgumentNullException.ThrowIfNull(appChanges); ArgumentNullException.ThrowIfNull(packageChanges); @@ -595,9 +586,7 @@ public static class PluginsCore { } internal static async Task OnPICSChangesRestart(uint currentChangeNumber) { - if (currentChangeNumber == 0) { - throw new ArgumentNullException(nameof(currentChangeNumber)); - } + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); if ((ActivePlugins == null) || (ActivePlugins.Count == 0)) { return; @@ -655,9 +644,7 @@ public static class PluginsCore { [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "We don't care about trimmed assemblies, as we need it to work only with the known (used) ones")] private static HashSet? LoadAssembliesFrom(string path) { - if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException(nameof(path)); - } + ArgumentException.ThrowIfNullOrEmpty(path); if (!Directory.Exists(path)) { return null; diff --git a/ArchiSteamFarm/Program.cs b/ArchiSteamFarm/Program.cs index d13aaa466..1b8fe4355 100644 --- a/ArchiSteamFarm/Program.cs +++ b/ArchiSteamFarm/Program.cs @@ -89,9 +89,7 @@ internal static class Program { string executableName = Path.GetFileNameWithoutExtension(OS.ProcessFileName); - if (string.IsNullOrEmpty(executableName)) { - throw new ArgumentNullException(nameof(executableName)); - } + ArgumentException.ThrowIfNullOrEmpty(executableName); IEnumerable arguments = Environment.GetCommandLineArgs().Skip(executableName.Equals(SharedInfo.AssemblyName, StringComparison.Ordinal) ? 1 : 0); @@ -109,17 +107,13 @@ internal static class Program { } private static void HandleCryptKeyArgument(string cryptKey) { - if (string.IsNullOrEmpty(cryptKey)) { - throw new ArgumentNullException(nameof(cryptKey)); - } + ArgumentException.ThrowIfNullOrEmpty(cryptKey); ArchiCryptoHelper.SetEncryptionKey(cryptKey); } private static async Task HandleCryptKeyFileArgument(string cryptKeyFile) { - if (string.IsNullOrEmpty(cryptKeyFile)) { - throw new ArgumentNullException(nameof(cryptKeyFile)); - } + ArgumentException.ThrowIfNullOrEmpty(cryptKeyFile); if (!File.Exists(cryptKeyFile)) { ASF.ArchiLogger.LogGenericError(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(cryptKeyFile))); @@ -149,17 +143,13 @@ internal static class Program { } private static void HandleNetworkGroupArgument(string networkGroup) { - if (string.IsNullOrEmpty(networkGroup)) { - throw new ArgumentNullException(nameof(networkGroup)); - } + ArgumentException.ThrowIfNullOrEmpty(networkGroup); NetworkGroup = networkGroup; } private static bool HandlePathArgument(string path) { - if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException(nameof(path)); - } + ArgumentException.ThrowIfNullOrEmpty(path); // Aid userspace and replace ~ with user's home directory if possible if (path.Contains('~', StringComparison.Ordinal)) { @@ -361,7 +351,7 @@ internal static class Program { string globalConfigFile = ASF.GetFilePath(ASF.EFileType.Config); if (string.IsNullOrEmpty(globalConfigFile)) { - throw new ArgumentNullException(nameof(globalConfigFile)); + throw new InvalidOperationException(nameof(globalConfigFile)); } string? latestJson = null; @@ -420,7 +410,7 @@ internal static class Program { string globalDatabaseFile = ASF.GetFilePath(ASF.EFileType.Database); if (string.IsNullOrEmpty(globalDatabaseFile)) { - throw new ArgumentNullException(nameof(globalDatabaseFile)); + throw new InvalidOperationException(nameof(globalDatabaseFile)); } if (!File.Exists(globalDatabaseFile)) { diff --git a/ArchiSteamFarm/SharedInfo.cs b/ArchiSteamFarm/SharedInfo.cs index 1b02392e4..87acc0132 100644 --- a/ArchiSteamFarm/SharedInfo.cs +++ b/ArchiSteamFarm/SharedInfo.cs @@ -68,6 +68,15 @@ public static class SharedInfo { internal const string UpdateDirectory = "_old"; internal const string WebsiteDirectory = "www"; + [PublicAPI] + public static readonly char[] ListElementSeparators = { ',' }; + + [PublicAPI] + public static readonly string[] NewLineIndicators = { "\r\n", "\r", "\n" }; + + [PublicAPI] + public static readonly string[] RangeIndicators = { ".." }; + internal static string HomeDirectory { get { if (!string.IsNullOrEmpty(CachedHomeDirectory)) { diff --git a/ArchiSteamFarm/Steam/Bot.cs b/ArchiSteamFarm/Steam/Bot.cs index 3d2571f5e..c4fd04b4d 100644 --- a/ArchiSteamFarm/Steam/Bot.cs +++ b/ArchiSteamFarm/Steam/Bot.cs @@ -284,14 +284,18 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } private Bot(string botName, BotConfig botConfig, BotDatabase botDatabase) { - BotName = !string.IsNullOrEmpty(botName) ? botName : throw new ArgumentNullException(nameof(botName)); - BotConfig = botConfig ?? throw new ArgumentNullException(nameof(botConfig)); - BotDatabase = botDatabase ?? throw new ArgumentNullException(nameof(botDatabase)); + ArgumentException.ThrowIfNullOrEmpty(botName); + ArgumentNullException.ThrowIfNull(botConfig); + ArgumentNullException.ThrowIfNull(botDatabase); if (ASF.GlobalDatabase == null) { throw new InvalidOperationException(nameof(ASF.GlobalDatabase)); } + BotName = botName; + BotConfig = botConfig; + BotDatabase = botDatabase; + ArchiLogger = new ArchiLogger(botName); BotDatabase.MobileAuthenticator?.Init(this); @@ -327,9 +331,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } } - SteamUnifiedMessages? steamUnifiedMessages = SteamClient.GetHandler(); - - ArchiHandler = new ArchiHandler(ArchiLogger, steamUnifiedMessages ?? throw new InvalidOperationException(nameof(steamUnifiedMessages))); + ArchiHandler = new ArchiHandler(ArchiLogger, SteamClient.GetHandler() ?? throw new InvalidOperationException(nameof(SteamUnifiedMessages))); SteamClient.AddHandler(ArchiHandler); CallbackManager = new CallbackManager(SteamClient); @@ -492,9 +494,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { [PublicAPI] public static Bot? GetBot(string botName) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(botName); if (Bots == null) { throw new InvalidOperationException(nameof(Bots)); @@ -513,9 +513,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { [PublicAPI] public static HashSet? GetBots(string args) { - if (string.IsNullOrEmpty(args)) { - throw new ArgumentNullException(nameof(args)); - } + ArgumentException.ThrowIfNullOrEmpty(args); if (Bots == null) { throw new InvalidOperationException(nameof(Bots)); @@ -525,7 +523,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new InvalidOperationException(nameof(BotsComparer)); } - string[] botNames = args.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] botNames = args.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); HashSet result = new(); @@ -537,8 +535,8 @@ public sealed class Bot : IAsyncDisposable, IDisposable { return result; } - if ((botName.Length > 2) && botName.Contains("..", StringComparison.Ordinal)) { - string[] botRange = botName.Split(new[] { ".." }, StringSplitOptions.RemoveEmptyEntries); + if ((botName.Length > 2) && SharedInfo.RangeIndicators.Any(rangeIndicator => botName.Contains(rangeIndicator, StringComparison.Ordinal))) { + string[] botRange = botName.Split(SharedInfo.RangeIndicators, StringSplitOptions.RemoveEmptyEntries); Bot? firstBot = GetBot(botRange[0]); @@ -619,9 +617,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { [PublicAPI] public static string GetFilePath(string botName, EFileType fileType) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(botName); if (!Enum.IsDefined(fileType)) { throw new InvalidEnumArgumentException(nameof(fileType), (int) fileType, typeof(EFileType)); @@ -636,7 +632,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { EFileType.KeysToRedeemUnused => $"{botPath}{SharedInfo.KeysExtension}{SharedInfo.KeysUnusedExtension}", EFileType.KeysToRedeemUsed => $"{botPath}{SharedInfo.KeysExtension}{SharedInfo.KeysUsedExtension}", EFileType.MobileAuthenticator => $"{botPath}{SharedInfo.MobileAuthenticatorExtension}", - _ => throw new ArgumentOutOfRangeException(nameof(fileType)) + _ => throw new InvalidOperationException(nameof(fileType)) }; } @@ -662,9 +658,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new ArgumentNullException(nameof(amountsToExtract)); } - if (maxItems < MinCardsPerBadge) { - throw new ArgumentOutOfRangeException(nameof(maxItems)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(maxItems, MinCardsPerBadge); HashSet result = new(); Dictionary<(uint RealAppID, Asset.EType Type, Asset.ERarity Rarity), Dictionary>> itemsPerClassIDPerSet = inventory.GroupBy(static item => (item.RealAppID, item.Type, item.Rarity)).ToDictionary(static grouping => grouping.Key, static grouping => grouping.GroupBy(static item => item.ClassID).ToDictionary(static group => group.Key, static group => group.ToHashSet())); @@ -792,9 +786,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (tradeID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeID); if (Bots == null) { throw new InvalidOperationException(nameof(Bots)); @@ -864,9 +856,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if (!IsConnectedAndLoggedOn) { return false; @@ -889,17 +879,9 @@ public sealed class Bot : IAsyncDisposable, IDisposable { [PublicAPI] public async Task SendMessage(ulong chatGroupID, ulong chatID, string message) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } - - if (chatID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatID)); - } - - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); + ArgumentOutOfRangeException.ThrowIfZero(chatID); + ArgumentException.ThrowIfNullOrEmpty(message); if (!IsConnectedAndLoggedOn) { return false; @@ -926,9 +908,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new InvalidEnumArgumentException(nameof(inputType), (int) inputType, typeof(ASF.EUserInputType)); } - if (string.IsNullOrEmpty(inputValue)) { - throw new ArgumentNullException(nameof(inputValue)); - } + ArgumentException.ThrowIfNullOrEmpty(inputValue); // This switch should cover ONLY bot properties switch (inputType) { @@ -990,7 +970,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { break; default: - throw new ArgumentOutOfRangeException(nameof(inputType)); + throw new InvalidOperationException(nameof(inputType)); } if (RequiredInput == inputType) { @@ -1074,25 +1054,15 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal static string FormatBotResponse(string response, string botName) { - if (string.IsNullOrEmpty(response)) { - throw new ArgumentNullException(nameof(response)); - } - - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(response); + ArgumentException.ThrowIfNullOrEmpty(botName); return $"{Environment.NewLine}<{botName}> {response}"; } internal async Task<(uint PlayableAppID, DateTime IgnoredUntil, bool IgnoredGlobally)> GetAppDataForIdling(uint appID, float hoursPlayed, bool allowRecursiveDiscovery = true, bool optimisticDiscovery = true) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (hoursPlayed < 0) { - throw new ArgumentOutOfRangeException(nameof(hoursPlayed)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfNegative(hoursPlayed); HashSet? packageIDs = ASF.GlobalDatabase?.GetPackageIDs(appID, OwnedPackageIDs.Keys); @@ -1270,7 +1240,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } // ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework - string[] dlcAppIDsTexts = listOfDlc!.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] dlcAppIDsTexts = listOfDlc!.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (string dlcAppIDsText in dlcAppIDsTexts) { if (!uint.TryParse(dlcAppIDsText, out uint dlcAppID) || (dlcAppID == 0)) { @@ -1441,8 +1411,10 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal async Task ImportKeysToRedeem(string filePath) { - if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { - throw new ArgumentNullException(nameof(filePath)); + ArgumentException.ThrowIfNullOrEmpty(filePath); + + if (!File.Exists(filePath)) { + throw new FileNotFoundException(nameof(filePath), filePath); } try { @@ -1488,19 +1460,18 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal static void Init(StringComparer botsComparer) { + ArgumentNullException.ThrowIfNull(botsComparer); + if (Bots != null) { throw new InvalidOperationException(nameof(Bots)); } - BotsComparer = botsComparer ?? throw new ArgumentNullException(nameof(botsComparer)); - + BotsComparer = botsComparer; Bots = new ConcurrentDictionary(botsComparer); } internal bool IsBlacklistedFromIdling(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); return BotDatabase.FarmingBlacklistAppIDs.Contains(appID); } @@ -1514,9 +1485,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal bool IsPriorityIdling(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); return BotDatabase.FarmingPriorityQueueAppIDs.Contains(appID); } @@ -1664,9 +1633,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal static async Task RegisterBot(string botName) { - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(botName); if (Bots == null) { throw new InvalidOperationException(nameof(Bots)); @@ -1780,9 +1747,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } internal async Task Rename(string newBotName) { - if (string.IsNullOrEmpty(newBotName)) { - throw new ArgumentNullException(nameof(newBotName)); - } + ArgumentException.ThrowIfNullOrEmpty(newBotName); if (Bots == null) { throw new InvalidOperationException(nameof(Bots)); @@ -2063,9 +2028,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } private async Task?> GetKeysFromFile(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { return new Dictionary(0, StringComparer.Ordinal); @@ -2110,9 +2073,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } private async Task?> GetPossiblyCompletedBadgeAppIDs(byte page) { - if (page == 0) { - throw new ArgumentOutOfRangeException(nameof(page)); - } + ArgumentOutOfRangeException.ThrowIfZero(page); using IDocument? badgePage = await ArchiWebHandler.GetBadgePage(page).ConfigureAwait(false); @@ -2503,9 +2464,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } private void InitRefreshTokensTimer(DateTime validUntil) { - if (validUntil == DateTime.MinValue) { - throw new ArgumentOutOfRangeException(nameof(validUntil)); - } + ArgumentOutOfRangeException.ThrowIfEqual(validUntil, DateTime.MinValue); if (validUntil == DateTime.MaxValue) { // OK, tokens do not require refreshing @@ -2559,7 +2518,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { private static bool IsRefundable(EPaymentMethod paymentMethod) { if (paymentMethod == EPaymentMethod.None) { - throw new ArgumentNullException(nameof(paymentMethod)); + throw new ArgumentOutOfRangeException(nameof(paymentMethod)); } #pragma warning disable CA2248 // This is actually a fair warning, EPaymentMethod is not a flags enum on itself, but there is nothing we can do about Steam using it like that here @@ -3754,9 +3713,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(messagePart)) { - throw new ArgumentNullException(nameof(messagePart)); - } + ArgumentException.ThrowIfNullOrEmpty(messagePart); if (!IsConnectedAndLoggedOn) { return false; @@ -3843,9 +3800,7 @@ public sealed class Bot : IAsyncDisposable, IDisposable { } private void UpdateTokens(string accessToken, string? refreshToken = null) { - if (string.IsNullOrEmpty(accessToken)) { - throw new ArgumentNullException(nameof(accessToken)); - } + ArgumentException.ThrowIfNullOrEmpty(accessToken); AccessToken = accessToken; diff --git a/ArchiSteamFarm/Steam/Cards/CardsFarmer.cs b/ArchiSteamFarm/Steam/Cards/CardsFarmer.cs index 938434e35..855d80e7e 100644 --- a/ArchiSteamFarm/Steam/Cards/CardsFarmer.cs +++ b/ArchiSteamFarm/Steam/Cards/CardsFarmer.cs @@ -148,7 +148,9 @@ public sealed class CardsFarmer : IAsyncDisposable, IDisposable { private bool ShouldSkipNewGamesIfPossible; internal CardsFarmer(Bot bot) { - Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; byte idleFarmingPeriod = ASF.GlobalConfig?.IdleFarmingPeriod ?? GlobalConfig.DefaultIdleFarmingPeriod; @@ -416,17 +418,9 @@ public sealed class CardsFarmer : IAsyncDisposable, IDisposable { } private async Task CheckGame(uint appID, string name, float hours, byte badgeLevel) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name)); - } - - if (hours < 0) { - throw new ArgumentOutOfRangeException(nameof(hours)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentOutOfRangeException.ThrowIfNegative(hours); Game? game = await GetGameCardsInfo(appID).ConfigureAwait(false); @@ -746,10 +740,7 @@ public sealed class CardsFarmer : IAsyncDisposable, IDisposable { } private async Task CheckPage(byte page, ISet parsedAppIDs) { - if (page == 0) { - throw new ArgumentOutOfRangeException(nameof(page)); - } - + ArgumentOutOfRangeException.ThrowIfZero(page); ArgumentNullException.ThrowIfNull(parsedAppIDs); using IDocument? htmlDocument = await Bot.ArchiWebHandler.GetBadgePage(page).ConfigureAwait(false); @@ -989,9 +980,7 @@ public sealed class CardsFarmer : IAsyncDisposable, IDisposable { } private async Task GetGameCardsInfo(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); using IDocument? htmlDocument = await Bot.ArchiWebHandler.GetGameCardsPage(appID).ConfigureAwait(false); @@ -1350,9 +1339,7 @@ public sealed class CardsFarmer : IAsyncDisposable, IDisposable { } private bool ShouldIdle(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); if (SalesBlacklist.Contains(appID) || (ASF.GlobalConfig?.Blacklist.Contains(appID) == true) || Bot.IsBlacklistedFromIdling(appID) || (Bot.BotConfig.FarmPriorityQueueOnly && !Bot.IsPriorityIdling(appID))) { // We're configured to ignore this appID, so skip it diff --git a/ArchiSteamFarm/Steam/Data/Asset.cs b/ArchiSteamFarm/Steam/Data/Asset.cs index 1b5933265..c84adcf74 100644 --- a/ArchiSteamFarm/Steam/Data/Asset.cs +++ b/ArchiSteamFarm/Steam/Data/Asset.cs @@ -196,21 +196,10 @@ public sealed class Asset { // Constructed from trades being received or plugins public Asset(uint appID, ulong contextID, ulong classID, uint amount, ulong instanceID = 0, ulong assetID = 0, bool marketable = true, bool tradable = true, ImmutableHashSet? tags = null, uint realAppID = 0, EType type = EType.Unknown, ERarity rarity = ERarity.Unknown) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (contextID == 0) { - throw new ArgumentOutOfRangeException(nameof(contextID)); - } - - if (classID == 0) { - throw new ArgumentOutOfRangeException(nameof(classID)); - } - - if (amount == 0) { - throw new ArgumentOutOfRangeException(nameof(amount)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfZero(contextID); + ArgumentOutOfRangeException.ThrowIfZero(classID); + ArgumentOutOfRangeException.ThrowIfZero(amount); AppID = appID; ContextID = contextID; diff --git a/ArchiSteamFarm/Steam/Data/Tag.cs b/ArchiSteamFarm/Steam/Data/Tag.cs index c547302f7..d13a6d8c7 100644 --- a/ArchiSteamFarm/Steam/Data/Tag.cs +++ b/ArchiSteamFarm/Steam/Data/Tag.cs @@ -35,8 +35,11 @@ public sealed class Tag { public string Value { get; private set; } = ""; internal Tag(string identifier, string value) { - Identifier = !string.IsNullOrEmpty(identifier) ? identifier : throw new ArgumentNullException(nameof(identifier)); - Value = value ?? throw new ArgumentNullException(nameof(value)); + ArgumentException.ThrowIfNullOrEmpty(identifier); + ArgumentNullException.ThrowIfNull(value); + + Identifier = identifier; + Value = value; } [JsonConstructor] diff --git a/ArchiSteamFarm/Steam/Data/TradeOffer.cs b/ArchiSteamFarm/Steam/Data/TradeOffer.cs index 38296b532..02717bd8b 100644 --- a/ArchiSteamFarm/Steam/Data/TradeOffer.cs +++ b/ArchiSteamFarm/Steam/Data/TradeOffer.cs @@ -50,13 +50,8 @@ public sealed class TradeOffer { // Constructed from trades being received internal TradeOffer(ulong tradeOfferID, uint otherSteamID3, ETradeOfferState state) { - if (tradeOfferID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeOfferID)); - } - - if (otherSteamID3 == 0) { - throw new ArgumentOutOfRangeException(nameof(otherSteamID3)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeOfferID); + ArgumentOutOfRangeException.ThrowIfZero(otherSteamID3); if (!Enum.IsDefined(state)) { throw new InvalidEnumArgumentException(nameof(state), (int) state, typeof(ETradeOfferState)); diff --git a/ArchiSteamFarm/Steam/Data/UserPrivacy.cs b/ArchiSteamFarm/Steam/Data/UserPrivacy.cs index bbd4ac008..cc34c3fa4 100644 --- a/ArchiSteamFarm/Steam/Data/UserPrivacy.cs +++ b/ArchiSteamFarm/Steam/Data/UserPrivacy.cs @@ -37,7 +37,13 @@ internal sealed class UserPrivacy { // Constructed from privacy change request internal UserPrivacy(PrivacySettings settings, ECommentPermission commentPermission) { - Settings = settings ?? throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(settings); + + if (!Enum.IsDefined(commentPermission)) { + throw new InvalidEnumArgumentException(nameof(commentPermission), (int) commentPermission, typeof(ECommentPermission)); + } + + Settings = settings; CommentPermission = commentPermission; } diff --git a/ArchiSteamFarm/Steam/Exchange/ParseTradeResult.cs b/ArchiSteamFarm/Steam/Exchange/ParseTradeResult.cs index 296e01ee7..06dacb8c8 100644 --- a/ArchiSteamFarm/Steam/Exchange/ParseTradeResult.cs +++ b/ArchiSteamFarm/Steam/Exchange/ParseTradeResult.cs @@ -44,9 +44,7 @@ public sealed class ParseTradeResult { public bool Confirmed { get; internal set; } internal ParseTradeResult(ulong tradeOfferID, EResult result, bool requiresMobileConfirmation, IReadOnlyCollection? itemsToGive = null, IReadOnlyCollection? itemsToReceive = null) { - if (tradeOfferID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeOfferID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeOfferID); if ((result == EResult.Unknown) || !Enum.IsDefined(result)) { throw new InvalidEnumArgumentException(nameof(result), (int) result, typeof(EResult)); diff --git a/ArchiSteamFarm/Steam/Exchange/Trading.cs b/ArchiSteamFarm/Steam/Exchange/Trading.cs index eb55e0b4a..9b0f0defe 100644 --- a/ArchiSteamFarm/Steam/Exchange/Trading.cs +++ b/ArchiSteamFarm/Steam/Exchange/Trading.cs @@ -49,7 +49,11 @@ public sealed class Trading : IDisposable { private bool ParsingScheduled; - internal Trading(Bot bot) => Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + internal Trading(Bot bot) { + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; + } public void Dispose() => TradesSemaphore.Dispose(); diff --git a/ArchiSteamFarm/Steam/Integration/ArchiHandler.cs b/ArchiSteamFarm/Steam/Integration/ArchiHandler.cs index d20ee25de..4c92e252e 100644 --- a/ArchiSteamFarm/Steam/Integration/ArchiHandler.cs +++ b/ArchiSteamFarm/Steam/Integration/ArchiHandler.cs @@ -51,9 +51,10 @@ public sealed class ArchiHandler : ClientMsgHandler { internal DateTime LastPacketReceived { get; private set; } internal ArchiHandler(ArchiLogger archiLogger, SteamUnifiedMessages steamUnifiedMessages) { + ArgumentNullException.ThrowIfNull(archiLogger); ArgumentNullException.ThrowIfNull(steamUnifiedMessages); - ArchiLogger = archiLogger ?? throw new ArgumentNullException(nameof(archiLogger)); + ArchiLogger = archiLogger; UnifiedChatRoomService = steamUnifiedMessages.CreateService(); UnifiedClanChatRoomsService = steamUnifiedMessages.CreateService(); UnifiedCredentialsService = steamUnifiedMessages.CreateService(); @@ -282,9 +283,7 @@ public sealed class ArchiHandler : ClientMsgHandler { [PublicAPI] public async Task JoinChatRoomGroup(ulong chatGroupID) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -311,9 +310,7 @@ public sealed class ArchiHandler : ClientMsgHandler { [PublicAPI] public async Task LeaveChatRoomGroup(ulong chatGroupID) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -368,17 +365,9 @@ public sealed class ArchiHandler : ClientMsgHandler { } internal void AckChatMessage(ulong chatGroupID, ulong chatID, uint timestamp) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } - - if (chatID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatID)); - } - - if (timestamp == 0) { - throw new ArgumentOutOfRangeException(nameof(timestamp)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); + ArgumentOutOfRangeException.ThrowIfZero(chatID); + ArgumentOutOfRangeException.ThrowIfZero(timestamp); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -402,9 +391,7 @@ public sealed class ArchiHandler : ClientMsgHandler { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (timestamp == 0) { - throw new ArgumentOutOfRangeException(nameof(timestamp)); - } + ArgumentOutOfRangeException.ThrowIfZero(timestamp); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -630,9 +617,7 @@ public sealed class ArchiHandler : ClientMsgHandler { } internal async Task RedeemGuestPass(ulong guestPassID) { - if (guestPassID == 0) { - throw new ArgumentOutOfRangeException(nameof(guestPassID)); - } + ArgumentOutOfRangeException.ThrowIfZero(guestPassID); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -659,9 +644,7 @@ public sealed class ArchiHandler : ClientMsgHandler { } internal async Task RedeemKey(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -708,9 +691,7 @@ public sealed class ArchiHandler : ClientMsgHandler { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -741,17 +722,9 @@ public sealed class ArchiHandler : ClientMsgHandler { } internal async Task SendMessage(ulong chatGroupID, ulong chatID, string message) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } - - if (chatID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatID)); - } - - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); + ArgumentOutOfRangeException.ThrowIfZero(chatID); + ArgumentException.ThrowIfNullOrEmpty(message); if (Client == null) { throw new InvalidOperationException(nameof(Client)); @@ -816,9 +789,7 @@ public sealed class ArchiHandler : ClientMsgHandler { throw new InvalidEnumArgumentException(nameof(userInterfaceMode), (int) userInterfaceMode, typeof(EUserInterfaceMode)); } - if (chatMode == 0) { - throw new ArgumentOutOfRangeException(nameof(chatMode)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatMode); if (Client == null) { throw new InvalidOperationException(nameof(Client)); diff --git a/ArchiSteamFarm/Steam/Integration/ArchiWebHandler.cs b/ArchiSteamFarm/Steam/Integration/ArchiWebHandler.cs index 95ed33f6e..85cd6b493 100644 --- a/ArchiSteamFarm/Steam/Integration/ArchiWebHandler.cs +++ b/ArchiSteamFarm/Steam/Integration/ArchiWebHandler.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; @@ -91,7 +92,9 @@ public sealed class ArchiWebHandler : IDisposable { private string? VanityURL; internal ArchiWebHandler(Bot bot) { - Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; CachedAccessToken = new ArchiCacheable(ResolveAccessToken, TimeSpan.FromHours(6)); CachedApiKey = new ArchiCacheable(ResolveApiKey, TimeSpan.FromHours(6)); @@ -110,9 +113,7 @@ public sealed class ArchiWebHandler : IDisposable { [PublicAPI] public async Task CancelTradeOffer(ulong tradeID) { - if (tradeID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeID); Uri request = new(SteamCommunityURL, $"/tradeoffer/{tradeID}/cancel"); @@ -242,13 +243,8 @@ public sealed class ArchiWebHandler : IDisposable { [PublicAPI] public async IAsyncEnumerable GetInventoryAsync(ulong steamID = 0, uint appID = Asset.SteamAppID, ulong contextID = Asset.SteamCommunityContextID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (contextID == 0) { - throw new ArgumentOutOfRangeException(nameof(contextID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfZero(contextID); if (ASF.InventorySemaphore == null) { throw new InvalidOperationException(nameof(ASF.InventorySemaphore)); @@ -708,9 +704,7 @@ public sealed class ArchiWebHandler : IDisposable { throw new ArgumentException($"{nameof(itemsToGive)} && {nameof(itemsToReceive)}"); } - if (itemsPerTrade <= 2) { - throw new ArgumentOutOfRangeException(nameof(itemsPerTrade)); - } + ArgumentOutOfRangeException.ThrowIfZero(itemsPerTrade); TradeOfferSendRequest singleTrade = new(); HashSet trades = new() { singleTrade }; @@ -810,14 +804,8 @@ public sealed class ArchiWebHandler : IDisposable { [PublicAPI] public async Task UrlGetToHtmlDocumentWithSession(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, WebBrowser.ERequestOptions requestOptions = WebBrowser.ERequestOptions.None, bool checkSessionPreemptively = true, byte maxTries = WebBrowser.MaxTries, int rateLimitingDelay = 0, bool allowSessionRefresh = true) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -898,14 +886,8 @@ public sealed class ArchiWebHandler : IDisposable { [PublicAPI] public async Task?> UrlGetToJsonObjectWithSession(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, WebBrowser.ERequestOptions requestOptions = WebBrowser.ERequestOptions.None, bool checkSessionPreemptively = true, byte maxTries = WebBrowser.MaxTries, int rateLimitingDelay = 0, bool allowSessionRefresh = true) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -986,14 +968,8 @@ public sealed class ArchiWebHandler : IDisposable { [PublicAPI] public async Task UrlHeadWithSession(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, WebBrowser.ERequestOptions requestOptions = WebBrowser.ERequestOptions.None, bool checkSessionPreemptively = true, byte maxTries = WebBrowser.MaxTries, int rateLimitingDelay = 0, bool allowSessionRefresh = true) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -1079,13 +1055,8 @@ public sealed class ArchiWebHandler : IDisposable { throw new InvalidEnumArgumentException(nameof(session), (int) session, typeof(ESession)); } - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -1141,7 +1112,7 @@ public sealed class ArchiWebHandler : IDisposable { ESession.CamelCase => "sessionID", ESession.Lowercase => "sessionid", ESession.PascalCase => "SessionID", - _ => throw new ArgumentOutOfRangeException(nameof(session)) + _ => throw new InvalidOperationException(nameof(session)) }; if (data != null) { @@ -1196,13 +1167,8 @@ public sealed class ArchiWebHandler : IDisposable { throw new InvalidEnumArgumentException(nameof(session), (int) session, typeof(ESession)); } - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -1258,7 +1224,7 @@ public sealed class ArchiWebHandler : IDisposable { ESession.CamelCase => "sessionID", ESession.Lowercase => "sessionid", ESession.PascalCase => "SessionID", - _ => throw new ArgumentOutOfRangeException(nameof(session)) + _ => throw new InvalidOperationException(nameof(session)) }; if (data != null) { @@ -1313,13 +1279,8 @@ public sealed class ArchiWebHandler : IDisposable { throw new InvalidEnumArgumentException(nameof(session), (int) session, typeof(ESession)); } - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -1375,7 +1336,7 @@ public sealed class ArchiWebHandler : IDisposable { ESession.CamelCase => "sessionID", ESession.Lowercase => "sessionid", ESession.PascalCase => "SessionID", - _ => throw new ArgumentOutOfRangeException(nameof(session)) + _ => throw new InvalidOperationException(nameof(session)) }; // ReSharper disable once RedundantSuppressNullableWarningExpression - required for .NET Framework @@ -1432,13 +1393,8 @@ public sealed class ArchiWebHandler : IDisposable { throw new InvalidEnumArgumentException(nameof(session), (int) session, typeof(ESession)); } - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); if (WebLimiterDelay > rateLimitingDelay) { rateLimitingDelay = WebLimiterDelay; @@ -1494,7 +1450,7 @@ public sealed class ArchiWebHandler : IDisposable { ESession.CamelCase => "sessionID", ESession.Lowercase => "sessionid", ESession.PascalCase => "SessionID", - _ => throw new ArgumentOutOfRangeException(nameof(session)) + _ => throw new InvalidOperationException(nameof(session)) }; if (data != null) { @@ -1588,9 +1544,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task AcceptDigitalGiftCard(ulong giftCardID) { - if (giftCardID == 0) { - throw new ArgumentOutOfRangeException(nameof(giftCardID)); - } + ArgumentOutOfRangeException.ThrowIfZero(giftCardID); Uri request = new(SteamStoreURL, "/gifts/0/resolvegiftcard"); @@ -1616,9 +1570,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task<(bool Success, bool RequiresMobileConfirmation)> AcceptTradeOffer(ulong tradeID) { - if (tradeID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeID); Uri request = new(SteamCommunityURL, $"/tradeoffer/{tradeID}/accept"); Uri referer = new(SteamCommunityURL, $"/tradeoffer/{tradeID}"); @@ -1658,9 +1610,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task<(EResult Result, EPurchaseResultDetail PurchaseResult)> AddFreeLicense(uint subID) { - if (subID == 0) { - throw new ArgumentOutOfRangeException(nameof(subID)); - } + ArgumentOutOfRangeException.ThrowIfZero(subID); Uri request = new(SteamStoreURL, $"/freelicense/addfreelicense/{subID}"); @@ -1757,9 +1707,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task ClearFromDiscoveryQueue(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); Uri request = new(SteamStoreURL, $"/app/{appID}"); @@ -1770,9 +1718,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task DeclineTradeOffer(ulong tradeID) { - if (tradeID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeID); Uri request = new(SteamCommunityURL, $"/tradeoffer/{tradeID}/decline"); @@ -1848,13 +1794,8 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task GetBadgePage(byte page, byte maxTries = WebBrowser.MaxTries) { - if (page == 0) { - throw new ArgumentOutOfRangeException(nameof(page)); - } - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } + ArgumentOutOfRangeException.ThrowIfZero(page); + ArgumentOutOfRangeException.ThrowIfZero(maxTries); Uri request = new(SteamCommunityURL, $"/my/badges?l=english&p={page}"); @@ -1864,9 +1805,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task GetCardCountForGame(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); if (ASF.GlobalDatabase?.CardCountsPerGame.TryGetValue(appID, out byte result) == true) { return result; @@ -1961,17 +1900,9 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task GetConfirmations(string deviceID, string confirmationHash, ulong time) { - if (string.IsNullOrEmpty(deviceID)) { - throw new ArgumentNullException(nameof(deviceID)); - } - - if (string.IsNullOrEmpty(confirmationHash)) { - throw new ArgumentNullException(nameof(confirmationHash)); - } - - if (time == 0) { - throw new ArgumentOutOfRangeException(nameof(time)); - } + ArgumentException.ThrowIfNullOrEmpty(deviceID); + ArgumentException.ThrowIfNullOrEmpty(confirmationHash); + ArgumentOutOfRangeException.ThrowIfZero(time); if (!Initialized) { byte connectionTimeout = ASF.GlobalConfig?.ConnectionTimeout ?? GlobalConfig.DefaultConnectionTimeout; @@ -2084,9 +2015,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task GetGameCardsPage(uint appID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); Uri request = new(SteamCommunityURL, $"/my/gamecards/{appID}?l=english"); @@ -2139,9 +2068,7 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task GetTradeHoldDurationForTrade(ulong tradeID) { - if (tradeID == 0) { - throw new ArgumentOutOfRangeException(nameof(tradeID)); - } + ArgumentOutOfRangeException.ThrowIfZero(tradeID); Uri request = new(SteamCommunityURL, $"/tradeoffer/{tradeID}?l=english"); @@ -2194,25 +2121,11 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task HandleConfirmation(string deviceID, string confirmationHash, ulong time, ulong confirmationID, ulong confirmationKey, bool accept) { - if (string.IsNullOrEmpty(deviceID)) { - throw new ArgumentNullException(nameof(deviceID)); - } - - if (string.IsNullOrEmpty(confirmationHash)) { - throw new ArgumentNullException(nameof(confirmationHash)); - } - - if (time == 0) { - throw new ArgumentOutOfRangeException(nameof(time)); - } - - if (confirmationID == 0) { - throw new ArgumentOutOfRangeException(nameof(confirmationID)); - } - - if (confirmationKey == 0) { - throw new ArgumentOutOfRangeException(nameof(confirmationKey)); - } + ArgumentException.ThrowIfNullOrEmpty(deviceID); + ArgumentException.ThrowIfNullOrEmpty(confirmationHash); + ArgumentOutOfRangeException.ThrowIfZero(time); + ArgumentOutOfRangeException.ThrowIfZero(confirmationID); + ArgumentOutOfRangeException.ThrowIfZero(confirmationKey); if (!Initialized) { byte connectionTimeout = ASF.GlobalConfig?.ConnectionTimeout ?? GlobalConfig.DefaultConnectionTimeout; @@ -2236,17 +2149,9 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task HandleConfirmations(string deviceID, string confirmationHash, ulong time, IReadOnlyCollection confirmations, bool accept) { - if (string.IsNullOrEmpty(deviceID)) { - throw new ArgumentNullException(nameof(deviceID)); - } - - if (string.IsNullOrEmpty(confirmationHash)) { - throw new ArgumentNullException(nameof(confirmationHash)); - } - - if (time == 0) { - throw new ArgumentOutOfRangeException(nameof(time)); - } + ArgumentException.ThrowIfNullOrEmpty(deviceID); + ArgumentException.ThrowIfNullOrEmpty(confirmationHash); + ArgumentOutOfRangeException.ThrowIfZero(time); if ((confirmations == null) || (confirmations.Count == 0)) { throw new ArgumentNullException(nameof(confirmations)); @@ -2298,9 +2203,7 @@ public sealed class ArchiWebHandler : IDisposable { throw new InvalidEnumArgumentException(nameof(universe), (int) universe, typeof(EUniverse)); } - if (string.IsNullOrEmpty(accessToken)) { - throw new ArgumentNullException(nameof(accessToken)); - } + ArgumentException.ThrowIfNullOrEmpty(accessToken); string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString(CultureInfo.InvariantCulture))); @@ -2399,9 +2302,7 @@ public sealed class ArchiWebHandler : IDisposable { internal void OnVanityURLChanged(string? vanityURL = null) => VanityURL = !string.IsNullOrEmpty(vanityURL) ? vanityURL : null; internal async Task<(EResult Result, EPurchaseResultDetail? PurchaseResult, string? BalanceText)?> RedeemWalletKey(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); Uri request = new(SteamStoreURL, "/account/ajaxredeemwalletcode"); @@ -2423,13 +2324,8 @@ public sealed class ArchiWebHandler : IDisposable { } internal async Task UnpackBooster(uint appID, ulong itemID) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (itemID == 0) { - throw new ArgumentOutOfRangeException(nameof(itemID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfZero(itemID); string? profileURL = await GetAbsoluteProfileURL().ConfigureAwait(false); @@ -2602,7 +2498,7 @@ public sealed class ArchiWebHandler : IDisposable { return uri.AbsolutePath.StartsWith("/login", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("lostauth", StringComparison.OrdinalIgnoreCase); } - private static bool ParseItems(IReadOnlyDictionary<(uint AppID, ulong ClassID, ulong InstanceID), InventoryResponse.Description> descriptions, IReadOnlyCollection input, ICollection output) { + private static bool ParseItems([SuppressMessage("ReSharper", "SuggestBaseTypeForParameter")] Dictionary<(uint AppID, ulong ClassID, ulong InstanceID), InventoryResponse.Description> descriptions, IReadOnlyCollection input, ICollection output) { ArgumentNullException.ThrowIfNull(descriptions); if ((input == null) || (input.Count == 0)) { @@ -2879,9 +2775,7 @@ public sealed class ArchiWebHandler : IDisposable { } private async Task UnlockParentalAccount(string parentalCode) { - if (string.IsNullOrEmpty(parentalCode)) { - throw new ArgumentNullException(nameof(parentalCode)); - } + ArgumentException.ThrowIfNullOrEmpty(parentalCode); Bot.ArchiLogger.LogGenericInfo(Strings.UnlockingParentalAccount); @@ -2900,10 +2794,7 @@ public sealed class ArchiWebHandler : IDisposable { private async Task UnlockParentalAccountForService(Uri service, string parentalCode, byte maxTries = WebBrowser.MaxTries) { ArgumentNullException.ThrowIfNull(service); - - if (string.IsNullOrEmpty(parentalCode)) { - throw new ArgumentNullException(nameof(parentalCode)); - } + ArgumentException.ThrowIfNullOrEmpty(parentalCode); Uri request = new(service, "/parental/ajaxunlock"); diff --git a/ArchiSteamFarm/Steam/Integration/BotCredentialsProvider.cs b/ArchiSteamFarm/Steam/Integration/BotCredentialsProvider.cs index cfb9adcb5..564b783c4 100644 --- a/ArchiSteamFarm/Steam/Integration/BotCredentialsProvider.cs +++ b/ArchiSteamFarm/Steam/Integration/BotCredentialsProvider.cs @@ -80,7 +80,7 @@ internal sealed class BotCredentialsProvider : IAuthenticator { Bot.ArchiLogger.LogGenericWarning(string.Format(CultureInfo.CurrentCulture, Strings.BotUnableToLogin, reason, reason)); if (++LoginFailures >= MaxLoginFailures) { - CancellationTokenSource.Cancel(); + await CancellationTokenSource.CancelAsync().ConfigureAwait(false); return ""; } @@ -89,7 +89,7 @@ internal sealed class BotCredentialsProvider : IAuthenticator { string? result = await Bot.RequestInput(inputType, previousCodeWasIncorrect).ConfigureAwait(false); if (string.IsNullOrEmpty(result)) { - CancellationTokenSource.Cancel(); + await CancellationTokenSource.CancelAsync().ConfigureAwait(false); } return result ?? ""; diff --git a/ArchiSteamFarm/Steam/Integration/SteamChatMessage.cs b/ArchiSteamFarm/Steam/Integration/SteamChatMessage.cs index a22b87cdf..dd052b325 100644 --- a/ArchiSteamFarm/Steam/Integration/SteamChatMessage.cs +++ b/ArchiSteamFarm/Steam/Integration/SteamChatMessage.cs @@ -40,9 +40,7 @@ internal static class SteamChatMessage { internal const byte ReservedEscapeMessageBytes = 5; // 2 characters total, escape one '\' of 1 byte and real one of up to 4 bytes internal static async IAsyncEnumerable GetMessageParts(string message, string? steamMessagePrefix = null, bool isAccountLimited = false) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); int prefixBytes = 0; int prefixLength = 0; @@ -188,35 +186,27 @@ internal static class SteamChatMessage { } internal static bool IsValidPrefix(string steamMessagePrefix) { - if (string.IsNullOrEmpty(steamMessagePrefix)) { - throw new ArgumentNullException(nameof(steamMessagePrefix)); - } + ArgumentException.ThrowIfNullOrEmpty(steamMessagePrefix); return GetMessagePrefixBytes(Escape(steamMessagePrefix)) <= MaxMessagePrefixBytes; } internal static string Unescape(string message) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); return message.Replace("\\[", "[", StringComparison.Ordinal).Replace("\\\\", "\\", StringComparison.Ordinal); } private static string Escape(string message) { - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); return message.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("[", "\\[", StringComparison.Ordinal); } private static int GetMessagePrefixBytes(string escapedSteamMessagePrefix) { - if (string.IsNullOrEmpty(escapedSteamMessagePrefix)) { - throw new ArgumentNullException(nameof(escapedSteamMessagePrefix)); - } + ArgumentException.ThrowIfNullOrEmpty(escapedSteamMessagePrefix); - string[] prefixLines = escapedSteamMessagePrefix.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); + string[] prefixLines = escapedSteamMessagePrefix.Split(SharedInfo.NewLineIndicators, StringSplitOptions.None); return prefixLines.Where(static prefixLine => prefixLine.Length > 0).Sum(Encoding.UTF8.GetByteCount) + ((prefixLines.Length - 1) * NewlineWeight); } diff --git a/ArchiSteamFarm/Steam/Integration/SteamSaleEvent.cs b/ArchiSteamFarm/Steam/Integration/SteamSaleEvent.cs index 4b8dc4944..0c797cdd7 100644 --- a/ArchiSteamFarm/Steam/Integration/SteamSaleEvent.cs +++ b/ArchiSteamFarm/Steam/Integration/SteamSaleEvent.cs @@ -37,7 +37,9 @@ internal sealed class SteamSaleEvent : IAsyncDisposable, IDisposable { private readonly Timer SaleEventTimer; internal SteamSaleEvent(Bot bot) { - Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; SaleEventTimer = new Timer( ExploreDiscoveryQueue, diff --git a/ArchiSteamFarm/Steam/Integration/SteamUtilities.cs b/ArchiSteamFarm/Steam/Integration/SteamUtilities.cs index c1585856e..f3a01090d 100644 --- a/ArchiSteamFarm/Steam/Integration/SteamUtilities.cs +++ b/ArchiSteamFarm/Steam/Integration/SteamUtilities.cs @@ -29,9 +29,7 @@ namespace ArchiSteamFarm.Steam.Integration; internal static class SteamUtilities { internal static EResult? InterpretError(string errorText) { - if (string.IsNullOrEmpty(errorText)) { - throw new ArgumentNullException(nameof(errorText)); - } + ArgumentException.ThrowIfNullOrEmpty(errorText); if (errorText.StartsWith("EYldRefreshAppIfNecessary", StringComparison.Ordinal)) { return EResult.ServiceUnavailable; diff --git a/ArchiSteamFarm/Steam/Interaction/Actions.cs b/ArchiSteamFarm/Steam/Interaction/Actions.cs index 1d938eac4..ba972b80c 100644 --- a/ArchiSteamFarm/Steam/Interaction/Actions.cs +++ b/ArchiSteamFarm/Steam/Interaction/Actions.cs @@ -54,7 +54,11 @@ public sealed class Actions : IAsyncDisposable, IDisposable { private bool ProcessingGiftsScheduled; private bool TradingScheduled; - internal Actions(Bot bot) => Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + internal Actions(Bot bot) { + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; + } public void Dispose() { // Those are objects that are always being created if constructor doesn't throw exception @@ -80,9 +84,7 @@ public sealed class Actions : IAsyncDisposable, IDisposable { throw new InvalidEnumArgumentException(nameof(cryptoMethod), (int) cryptoMethod, typeof(ArchiCryptoHelper.ECryptoMethod)); } - if (string.IsNullOrEmpty(stringToEncrypt)) { - throw new ArgumentNullException(nameof(stringToEncrypt)); - } + ArgumentException.ThrowIfNullOrEmpty(stringToEncrypt); return ArchiCryptoHelper.Encrypt(cryptoMethod, stringToEncrypt); } @@ -222,9 +224,7 @@ public sealed class Actions : IAsyncDisposable, IDisposable { throw new InvalidEnumArgumentException(nameof(hashingMethod), (int) hashingMethod, typeof(ArchiCryptoHelper.EHashingMethod)); } - if (string.IsNullOrEmpty(stringToHash)) { - throw new ArgumentNullException(nameof(stringToHash)); - } + ArgumentException.ThrowIfNullOrEmpty(stringToHash); return ArchiCryptoHelper.Hash(hashingMethod, stringToHash); } @@ -319,9 +319,7 @@ public sealed class Actions : IAsyncDisposable, IDisposable { throw new ArgumentNullException(nameof(items)); } - if (itemsPerTrade < 2) { - throw new ArgumentOutOfRangeException(nameof(itemsPerTrade)); - } + ArgumentOutOfRangeException.ThrowIfZero(itemsPerTrade); if (!Bot.IsConnectedAndLoggedOn) { return (false, Strings.BotNotConnected); @@ -375,13 +373,8 @@ public sealed class Actions : IAsyncDisposable, IDisposable { [PublicAPI] public async Task<(bool Success, string Message)> SendInventory(uint appID = Asset.SteamAppID, ulong contextID = Asset.SteamCommunityContextID, ulong targetSteamID = 0, string? tradeToken = null, Func? filterFunction = null, ushort itemsPerTrade = Trading.MaxItemsPerTrade) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (contextID == 0) { - throw new ArgumentOutOfRangeException(nameof(contextID)); - } + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfZero(contextID); if (!Bot.IsConnectedAndLoggedOn) { return (false, Strings.BotNotConnected); diff --git a/ArchiSteamFarm/Steam/Interaction/Commands.cs b/ArchiSteamFarm/Steam/Interaction/Commands.cs index c5f182642..7a4451e60 100644 --- a/ArchiSteamFarm/Steam/Interaction/Commands.cs +++ b/ArchiSteamFarm/Steam/Interaction/Commands.cs @@ -49,35 +49,30 @@ public sealed class Commands { private readonly Bot Bot; private readonly Dictionary CachedGamesOwned = new(); - internal Commands(Bot bot) => Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + internal Commands(Bot bot) { + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; + } [PublicAPI] public static string FormatBotResponse(string response, string botName) { - if (string.IsNullOrEmpty(response)) { - throw new ArgumentNullException(nameof(response)); - } - - if (string.IsNullOrEmpty(botName)) { - throw new ArgumentNullException(nameof(botName)); - } + ArgumentException.ThrowIfNullOrEmpty(response); + ArgumentException.ThrowIfNullOrEmpty(botName); return $"{Environment.NewLine}<{botName}> {response}"; } [PublicAPI] public string FormatBotResponse(string response) { - if (string.IsNullOrEmpty(response)) { - throw new ArgumentNullException(nameof(response)); - } + ArgumentException.ThrowIfNullOrEmpty(response); return $"<{Bot.BotName}> {response}"; } [PublicAPI] public static string FormatStaticResponse(string response) { - if (string.IsNullOrEmpty(response)) { - throw new ArgumentNullException(nameof(response)); - } + ArgumentException.ThrowIfNullOrEmpty(response); return $"<{SharedInfo.ASF}> {response}"; } @@ -112,9 +107,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); string[] args = message.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries); @@ -345,9 +338,7 @@ public sealed class Commands { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); string? commandPrefix = ASF.GlobalConfig != null ? ASF.GlobalConfig.CommandPrefix : GlobalConfig.DefaultCommandPrefix; @@ -412,21 +403,14 @@ public sealed class Commands { } internal async Task HandleMessage(ulong chatGroupID, ulong chatID, ulong steamID, string message) { - if (chatGroupID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatGroupID)); - } - - if (chatID == 0) { - throw new ArgumentOutOfRangeException(nameof(chatID)); - } + ArgumentOutOfRangeException.ThrowIfZero(chatGroupID); + ArgumentOutOfRangeException.ThrowIfZero(chatID); if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); } - if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException(nameof(message)); - } + ArgumentException.ThrowIfNullOrEmpty(message); string? commandPrefix = ASF.GlobalConfig != null ? ASF.GlobalConfig.CommandPrefix : GlobalConfig.DefaultCommandPrefix; @@ -546,9 +530,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -590,9 +572,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -612,9 +592,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(query)) { - throw new ArgumentNullException(nameof(query)); - } + ArgumentException.ThrowIfNullOrEmpty(query); if (access < EAccess.Operator) { return null; @@ -626,7 +604,7 @@ public sealed class Commands { StringBuilder response = new(); - string[] entries = query.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] entries = query.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (string entry in entries) { uint gameID; @@ -697,13 +675,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(query)) { - throw new ArgumentNullException(nameof(query)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(query); HashSet? bots = Bot.GetBots(botNames); @@ -723,13 +696,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppID)) { - throw new ArgumentNullException(nameof(targetAppID)); - } - - if (string.IsNullOrEmpty(targetContextID)) { - throw new ArgumentNullException(nameof(targetContextID)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppID); + ArgumentException.ThrowIfNullOrEmpty(targetContextID); if (access < EAccess.Master) { return null; @@ -757,17 +725,9 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(appID)) { - throw new ArgumentNullException(nameof(appID)); - } - - if (string.IsNullOrEmpty(contextID)) { - throw new ArgumentNullException(nameof(contextID)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(appID); + ArgumentException.ThrowIfNullOrEmpty(contextID); HashSet? bots = Bot.GetBots(botNames); @@ -787,19 +747,14 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(options)) { - throw new ArgumentNullException(nameof(options)); - } - - if (string.IsNullOrEmpty(keys)) { - throw new ArgumentNullException(nameof(keys)); - } + ArgumentException.ThrowIfNullOrEmpty(options); + ArgumentException.ThrowIfNullOrEmpty(keys); if (access < EAccess.Operator) { return null; } - string[] flags = options.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] flags = options.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (flags.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(flags))); @@ -862,17 +817,9 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(options)) { - throw new ArgumentNullException(nameof(options)); - } - - if (string.IsNullOrEmpty(keys)) { - throw new ArgumentNullException(nameof(keys)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(options); + ArgumentException.ThrowIfNullOrEmpty(keys); HashSet? bots = Bot.GetBots(botNames); @@ -892,14 +839,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - - if (contextID == 0) { - throw new ArgumentOutOfRangeException(nameof(contextID)); - } - + ArgumentOutOfRangeException.ThrowIfZero(appID); + ArgumentOutOfRangeException.ThrowIfZero(contextID); ArgumentNullException.ThrowIfNull(targetBot); if (access < EAccess.Master) { @@ -924,17 +865,9 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppID)) { - throw new ArgumentNullException(nameof(targetAppID)); - } - - if (string.IsNullOrEmpty(targetContextID)) { - throw new ArgumentNullException(nameof(targetContextID)); - } - - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppID); + ArgumentException.ThrowIfNullOrEmpty(targetContextID); + ArgumentException.ThrowIfNullOrEmpty(botNameTo); Bot? targetBot = Bot.GetBot(botNameTo); @@ -958,21 +891,10 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppID)) { - throw new ArgumentNullException(nameof(targetAppID)); - } - - if (string.IsNullOrEmpty(targetContextID)) { - throw new ArgumentNullException(nameof(targetContextID)); - } - - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppID); + ArgumentException.ThrowIfNullOrEmpty(targetContextID); + ArgumentException.ThrowIfNullOrEmpty(botNameTo); HashSet? bots = Bot.GetBots(botNames); @@ -1020,9 +942,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1042,13 +962,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(cryptoMethodText)) { - throw new ArgumentNullException(nameof(cryptoMethodText)); - } - - if (string.IsNullOrEmpty(stringToEncrypt)) { - throw new ArgumentNullException(nameof(stringToEncrypt)); - } + ArgumentException.ThrowIfNullOrEmpty(cryptoMethodText); + ArgumentException.ThrowIfNullOrEmpty(stringToEncrypt); if (access < EAccess.Owner) { return null; @@ -1104,9 +1019,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1134,9 +1047,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1156,15 +1067,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1201,13 +1110,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1227,15 +1131,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1267,13 +1169,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1301,9 +1198,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1323,15 +1218,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1375,13 +1268,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1401,15 +1289,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1446,13 +1332,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1472,13 +1353,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(hashingMethodText)) { - throw new ArgumentNullException(nameof(hashingMethodText)); - } - - if (string.IsNullOrEmpty(stringToHash)) { - throw new ArgumentNullException(nameof(stringToHash)); - } + ArgumentException.ThrowIfNullOrEmpty(hashingMethodText); + ArgumentException.ThrowIfNullOrEmpty(stringToHash); if (access < EAccess.Owner) { return null; @@ -1506,13 +1382,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(propertyName)) { - throw new ArgumentNullException(nameof(propertyName)); - } - - if (string.IsNullOrEmpty(inputValue)) { - throw new ArgumentNullException(nameof(inputValue)); - } + ArgumentException.ThrowIfNullOrEmpty(propertyName); + ArgumentException.ThrowIfNullOrEmpty(inputValue); if (access < EAccess.Master) { return null; @@ -1538,17 +1409,9 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(propertyName)) { - throw new ArgumentNullException(nameof(propertyName)); - } - - if (string.IsNullOrEmpty(inputValue)) { - throw new ArgumentNullException(nameof(inputValue)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(propertyName); + ArgumentException.ThrowIfNullOrEmpty(inputValue); HashSet? bots = Bot.GetBots(botNames); @@ -1586,9 +1449,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1630,9 +1491,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1652,9 +1511,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(realAppIDsText)) { - throw new ArgumentNullException(nameof(realAppIDsText)); - } + ArgumentException.ThrowIfNullOrEmpty(realAppIDsText); if (access < EAccess.Master) { return null; @@ -1668,7 +1525,7 @@ public sealed class Commands { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(Bot.BotConfig.LootableTypes))); } - string[] appIDTexts = realAppIDsText.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] appIDTexts = realAppIDsText.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (appIDTexts.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(appIDTexts))); @@ -1694,13 +1551,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(realAppIDsText)) { - throw new ArgumentNullException(nameof(realAppIDsText)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(realAppIDsText); HashSet? bots = Bot.GetBots(botNames); @@ -1728,9 +1580,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -1750,15 +1600,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1782,13 +1630,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1808,15 +1651,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetAppIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetAppIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -1840,13 +1681,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetAppIDs)) { - throw new ArgumentNullException(nameof(targetAppIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetAppIDs); HashSet? bots = Bot.GetBots(botNames); @@ -1866,9 +1702,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(nickname)) { - throw new ArgumentNullException(nameof(nickname)); - } + ArgumentException.ThrowIfNullOrEmpty(nickname); if (access < EAccess.Master) { return null; @@ -1891,13 +1725,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(nickname)) { - throw new ArgumentNullException(nameof(nickname)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(nickname); HashSet? bots = Bot.GetBots(botNames); @@ -1917,9 +1746,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(query)) { - throw new ArgumentNullException(nameof(query)); - } + ArgumentException.ThrowIfNullOrEmpty(query); if (access < EAccess.Operator) { return (null, null); @@ -1934,7 +1761,7 @@ public sealed class Commands { StringBuilder response = new(); Dictionary result = new(StringComparer.Ordinal); - string[] entries = query.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] entries = query.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (string entry in entries) { string game; @@ -2066,13 +1893,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(query)) { - throw new ArgumentNullException(nameof(query)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(query); HashSet? bots = Bot.GetBots(botNames); @@ -2138,9 +1960,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2184,9 +2004,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetGameIDs)) { - throw new ArgumentNullException(nameof(targetGameIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetGameIDs); if (access < EAccess.Master) { return null; @@ -2196,7 +2014,7 @@ public sealed class Commands { return FormatBotResponse(Strings.BotNotConnected); } - string[] games = targetGameIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] games = targetGameIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (games.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(games))); @@ -2231,13 +2049,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetGameIDs)) { - throw new ArgumentNullException(nameof(targetGameIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetGameIDs); HashSet? bots = Bot.GetBots(botNames); @@ -2275,9 +2088,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2297,9 +2108,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(privacySettingsText)) { - throw new ArgumentNullException(nameof(privacySettingsText)); - } + ArgumentException.ThrowIfNullOrEmpty(privacySettingsText); if (access < EAccess.Master) { return null; @@ -2312,7 +2121,7 @@ public sealed class Commands { // There are only 7 privacy settings const byte privacySettings = 7; - string[] privacySettingsArgs = privacySettingsText.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] privacySettingsArgs = privacySettingsText.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); switch (privacySettingsArgs.Length) { case 0: @@ -2431,13 +2240,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(privacySettingsText)) { - throw new ArgumentNullException(nameof(privacySettingsText)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(privacySettingsText); HashSet? bots = Bot.GetBots(botNames); @@ -2457,9 +2261,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(keysText)) { - throw new ArgumentNullException(nameof(keysText)); - } + ArgumentException.ThrowIfNullOrEmpty(keysText); if ((steamID != 0) && !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); @@ -2477,7 +2279,7 @@ public sealed class Commands { return FormatBotResponse(Strings.BotNotConnected); } - string[] keys = keysText.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] keys = keysText.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (keys.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(keys))); @@ -2726,13 +2528,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(keysText)) { - throw new ArgumentNullException(nameof(keysText)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(keysText); HashSet? bots = Bot.GetBots(botNames); @@ -2770,9 +2567,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2820,9 +2615,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2856,9 +2649,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2935,9 +2726,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -2979,9 +2768,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -3009,9 +2796,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -3031,15 +2816,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetSteamIDs)) { - throw new ArgumentNullException(nameof(targetSteamIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetSteamIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetSteamIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetSteamIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -3063,13 +2846,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetSteamIDs)) { - throw new ArgumentNullException(nameof(targetSteamIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetSteamIDs); HashSet? bots = Bot.GetBots(botNames); @@ -3089,15 +2867,13 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(targetSteamIDs)) { - throw new ArgumentNullException(nameof(targetSteamIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(targetSteamIDs); if (access < EAccess.Master) { return null; } - string[] targets = targetSteamIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] targets = targetSteamIDs.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (targets.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(targets))); @@ -3121,13 +2897,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(targetSteamIDs)) { - throw new ArgumentNullException(nameof(targetSteamIDs)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(targetSteamIDs); HashSet? bots = Bot.GetBots(botNames); @@ -3147,9 +2918,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(botNameTo); if (access < EAccess.Master) { return null; @@ -3187,13 +2956,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(botNameTo); HashSet? bots = Bot.GetBots(botNames); @@ -3249,13 +3013,8 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(realAppIDsText)) { - throw new ArgumentNullException(nameof(realAppIDsText)); - } - - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(realAppIDsText); + ArgumentException.ThrowIfNullOrEmpty(botNameTo); if (access < EAccess.Master) { return null; @@ -3267,7 +3026,7 @@ public sealed class Commands { return access >= EAccess.Owner ? FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNameTo)) : null; } - string[] appIDTexts = realAppIDsText.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] appIDTexts = realAppIDsText.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (appIDTexts.Length == 0) { return FormatBotResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(appIDTexts))); @@ -3291,17 +3050,9 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } - - if (string.IsNullOrEmpty(realAppIDsText)) { - throw new ArgumentNullException(nameof(realAppIDsText)); - } - - if (string.IsNullOrEmpty(botNameTo)) { - throw new ArgumentNullException(nameof(botNameTo)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); + ArgumentException.ThrowIfNullOrEmpty(realAppIDsText); + ArgumentException.ThrowIfNullOrEmpty(botNameTo); HashSet? bots = Bot.GetBots(botNames); @@ -3309,7 +3060,7 @@ public sealed class Commands { return access >= EAccess.Owner ? FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.BotNotFound, botNames)) : null; } - string[] appIDTexts = realAppIDsText.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] appIDTexts = realAppIDsText.Split(SharedInfo.ListElementSeparators, StringSplitOptions.RemoveEmptyEntries); if (appIDTexts.Length == 0) { return FormatStaticResponse(string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsEmpty, nameof(appIDTexts))); @@ -3387,9 +3138,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); @@ -3452,9 +3201,7 @@ public sealed class Commands { throw new InvalidEnumArgumentException(nameof(access), (int) access, typeof(EAccess)); } - if (string.IsNullOrEmpty(botNames)) { - throw new ArgumentNullException(nameof(botNames)); - } + ArgumentException.ThrowIfNullOrEmpty(botNames); HashSet? bots = Bot.GetBots(botNames); diff --git a/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs b/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs index 93021e4ba..38000adb9 100644 --- a/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs +++ b/ArchiSteamFarm/Steam/Security/MobileAuthenticator.cs @@ -84,9 +84,7 @@ public sealed class MobileAuthenticator : IDisposable { } internal string? GenerateTokenForTime(ulong time) { - if (time == 0) { - throw new ArgumentOutOfRangeException(nameof(time)); - } + ArgumentOutOfRangeException.ThrowIfZero(time); if (Bot == null) { throw new InvalidOperationException(nameof(Bot)); @@ -287,7 +285,11 @@ public sealed class MobileAuthenticator : IDisposable { return true; } - internal void Init(Bot bot) => Bot = bot ?? throw new ArgumentNullException(nameof(bot)); + internal void Init(Bot bot) { + ArgumentNullException.ThrowIfNull(bot); + + Bot = bot; + } internal static async Task ResetSteamTimeDifference() { if ((SteamTimeDifference == null) && (LastSteamTimeCheck == DateTime.MinValue)) { @@ -312,9 +314,7 @@ public sealed class MobileAuthenticator : IDisposable { } private string? GenerateConfirmationHash(ulong time, string? tag = null) { - if (time == 0) { - throw new ArgumentOutOfRangeException(nameof(time)); - } + ArgumentOutOfRangeException.ThrowIfZero(time); if (Bot == null) { throw new InvalidOperationException(nameof(Bot)); diff --git a/ArchiSteamFarm/Steam/SteamKit2/ServerRecordEndPoint.cs b/ArchiSteamFarm/Steam/SteamKit2/ServerRecordEndPoint.cs index db9413e4d..eaf4f20bc 100644 --- a/ArchiSteamFarm/Steam/SteamKit2/ServerRecordEndPoint.cs +++ b/ArchiSteamFarm/Steam/SteamKit2/ServerRecordEndPoint.cs @@ -37,13 +37,8 @@ internal sealed class ServerRecordEndPoint : IEquatable { internal readonly ProtocolTypes ProtocolTypes; internal ServerRecordEndPoint(string host, ushort port, ProtocolTypes protocolTypes) { - if (string.IsNullOrEmpty(host)) { - throw new ArgumentNullException(nameof(host)); - } - - if (port == 0) { - throw new ArgumentOutOfRangeException(nameof(port)); - } + ArgumentException.ThrowIfNullOrEmpty(host); + ArgumentOutOfRangeException.ThrowIfZero(port); if (protocolTypes == 0) { throw new InvalidEnumArgumentException(nameof(protocolTypes), (int) protocolTypes, typeof(ProtocolTypes)); diff --git a/ArchiSteamFarm/Steam/Storage/BotConfig.cs b/ArchiSteamFarm/Steam/Storage/BotConfig.cs index 075dd53c8..9604e5553 100644 --- a/ArchiSteamFarm/Steam/Storage/BotConfig.cs +++ b/ArchiSteamFarm/Steam/Storage/BotConfig.cs @@ -438,10 +438,7 @@ public sealed class BotConfig { [PublicAPI] public static async Task Write(string filePath, BotConfig botConfig) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } - + ArgumentException.ThrowIfNullOrEmpty(filePath); ArgumentNullException.ThrowIfNull(botConfig); string json = JsonConvert.SerializeObject(botConfig, Formatting.Indented); @@ -572,9 +569,7 @@ public sealed class BotConfig { } internal static async Task<(BotConfig? BotConfig, string? LatestJson)> Load(string filePath, string? botName = null) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { return (null, null); diff --git a/ArchiSteamFarm/Steam/Storage/BotDatabase.cs b/ArchiSteamFarm/Steam/Storage/BotDatabase.cs index 570622504..f03e643dd 100644 --- a/ArchiSteamFarm/Steam/Storage/BotDatabase.cs +++ b/ArchiSteamFarm/Steam/Storage/BotDatabase.cs @@ -132,13 +132,7 @@ public sealed class BotDatabase : GenericDatabase { [JsonProperty] private string? BackingSteamGuardData; - private BotDatabase(string filePath) : this() { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } - - FilePath = filePath; - } + private BotDatabase(string filePath) : this() => FilePath = !string.IsNullOrEmpty(filePath) ? filePath : throw new ArgumentNullException(nameof(filePath)); [JsonConstructor] private BotDatabase() { @@ -221,9 +215,7 @@ public sealed class BotDatabase : GenericDatabase { } internal static async Task CreateOrLoad(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { return new BotDatabase(filePath); @@ -277,9 +269,7 @@ public sealed class BotDatabase : GenericDatabase { } internal void RemoveGameToRedeemInBackground(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); lock (GamesToRedeemInBackground) { if (!GamesToRedeemInBackground.Contains(key)) { diff --git a/ArchiSteamFarm/Storage/GenericDatabase.cs b/ArchiSteamFarm/Storage/GenericDatabase.cs index 96815b176..b0724b39a 100644 --- a/ArchiSteamFarm/Storage/GenericDatabase.cs +++ b/ArchiSteamFarm/Storage/GenericDatabase.cs @@ -35,9 +35,7 @@ public abstract class GenericDatabase : SerializableFile { [PublicAPI] public void DeleteFromJsonStorage(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); if (!KeyValueJsonStorage.TryRemove(key, out _)) { return; @@ -48,19 +46,14 @@ public abstract class GenericDatabase : SerializableFile { [PublicAPI] public JToken? LoadFromJsonStorage(string key) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } + ArgumentException.ThrowIfNullOrEmpty(key); return KeyValueJsonStorage.TryGetValue(key, out JToken? value) ? value : null; } [PublicAPI] public void SaveToJsonStorage(string key, JToken value) { - if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException(nameof(key)); - } - + ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(value); if (value.Type == JTokenType.Null) { diff --git a/ArchiSteamFarm/Storage/GlobalConfig.cs b/ArchiSteamFarm/Storage/GlobalConfig.cs index 0107e8e61..2e708b777 100644 --- a/ArchiSteamFarm/Storage/GlobalConfig.cs +++ b/ArchiSteamFarm/Storage/GlobalConfig.cs @@ -488,9 +488,7 @@ public sealed class GlobalConfig { } internal static async Task<(GlobalConfig? GlobalConfig, string? LatestJson)> Load(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { return (null, null); @@ -566,10 +564,7 @@ public sealed class GlobalConfig { } internal static async Task Write(string filePath, GlobalConfig globalConfig) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } - + ArgumentException.ThrowIfNullOrEmpty(filePath); ArgumentNullException.ThrowIfNull(globalConfig); string json = JsonConvert.SerializeObject(globalConfig, Formatting.Indented); diff --git a/ArchiSteamFarm/Storage/GlobalDatabase.cs b/ArchiSteamFarm/Storage/GlobalDatabase.cs index 2807806a5..7a3c4d09e 100644 --- a/ArchiSteamFarm/Storage/GlobalDatabase.cs +++ b/ArchiSteamFarm/Storage/GlobalDatabase.cs @@ -100,9 +100,7 @@ public sealed class GlobalDatabase : GenericDatabase { private uint BackingLastChangeNumber; private GlobalDatabase(string filePath) : this() { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); FilePath = filePath; } @@ -151,9 +149,7 @@ public sealed class GlobalDatabase : GenericDatabase { } internal static async Task CreateOrLoad(string filePath) { - if (string.IsNullOrEmpty(filePath)) { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentException.ThrowIfNullOrEmpty(filePath); if (!File.Exists(filePath)) { GlobalDatabase result = new(filePath); @@ -193,10 +189,7 @@ public sealed class GlobalDatabase : GenericDatabase { } internal HashSet GetPackageIDs(uint appID, IEnumerable packageIDs, int limit = int.MaxValue) { - if (appID == 0) { - throw new ArgumentOutOfRangeException(nameof(appID)); - } - + ArgumentOutOfRangeException.ThrowIfZero(appID); ArgumentNullException.ThrowIfNull(packageIDs); HashSet result = new(); @@ -217,9 +210,7 @@ public sealed class GlobalDatabase : GenericDatabase { } internal async Task OnPICSChangesRestart(uint currentChangeNumber) { - if (currentChangeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(currentChangeNumber)); - } + ArgumentOutOfRangeException.ThrowIfZero(currentChangeNumber); if (Bot.Bots == null) { throw new InvalidOperationException(nameof(Bot.Bots)); diff --git a/ArchiSteamFarm/Storage/PackageData.cs b/ArchiSteamFarm/Storage/PackageData.cs index 12bfe96e4..0c4cc8b5f 100644 --- a/ArchiSteamFarm/Storage/PackageData.cs +++ b/ArchiSteamFarm/Storage/PackageData.cs @@ -40,13 +40,8 @@ public sealed class PackageData { public DateTime ValidUntil { get; private set; } internal PackageData(uint changeNumber, DateTime validUntil, ImmutableHashSet? appIDs = null, ImmutableHashSet? prohibitRunInCountries = null) { - if (changeNumber == 0) { - throw new ArgumentOutOfRangeException(nameof(changeNumber)); - } - - if (validUntil == DateTime.MinValue) { - throw new ArgumentOutOfRangeException(nameof(validUntil)); - } + ArgumentOutOfRangeException.ThrowIfZero(changeNumber); + ArgumentOutOfRangeException.ThrowIfEqual(validUntil, DateTime.MinValue); ChangeNumber = changeNumber; ValidUntil = validUntil; diff --git a/ArchiSteamFarm/TrimmerRoots.xml b/ArchiSteamFarm/TrimmerRoots.xml index 1ef094166..cb56809e5 100644 --- a/ArchiSteamFarm/TrimmerRoots.xml +++ b/ArchiSteamFarm/TrimmerRoots.xml @@ -1,5 +1,5 @@ - + diff --git a/ArchiSteamFarm/Web/GitHub.cs b/ArchiSteamFarm/Web/GitHub.cs index 302e96f71..9c50bc509 100644 --- a/ArchiSteamFarm/Web/GitHub.cs +++ b/ArchiSteamFarm/Web/GitHub.cs @@ -53,9 +53,7 @@ internal static class GitHub { } internal static async Task GetRelease(string version) { - if (string.IsNullOrEmpty(version)) { - throw new ArgumentNullException(nameof(version)); - } + ArgumentException.ThrowIfNullOrEmpty(version); Uri request = new($"{SharedInfo.GithubReleaseURL}/tags/{version}"); @@ -63,9 +61,7 @@ internal static class GitHub { } internal static async Task?> GetWikiHistory(string page) { - if (string.IsNullOrEmpty(page)) { - throw new ArgumentNullException(nameof(page)); - } + ArgumentException.ThrowIfNullOrEmpty(page); if (ASF.WebBrowser == null) { throw new InvalidOperationException(nameof(ASF.WebBrowser)); @@ -137,9 +133,7 @@ internal static class GitHub { } internal static async Task GetWikiPage(string page, string? revision = null) { - if (string.IsNullOrEmpty(page)) { - throw new ArgumentNullException(nameof(page)); - } + ArgumentException.ThrowIfNullOrEmpty(page); if (ASF.WebBrowser == null) { throw new InvalidOperationException(nameof(ASF.WebBrowser)); @@ -159,9 +153,7 @@ internal static class GitHub { } private static MarkdownDocument ExtractChangelogFromBody(string markdownText) { - if (string.IsNullOrEmpty(markdownText)) { - throw new ArgumentNullException(nameof(markdownText)); - } + ArgumentException.ThrowIfNullOrEmpty(markdownText); MarkdownDocument markdownDocument = Markdown.Parse(markdownText); MarkdownDocument result = new(); diff --git a/ArchiSteamFarm/Web/Responses/BinaryResponse.cs b/ArchiSteamFarm/Web/Responses/BinaryResponse.cs index c1ce12e32..d5a430726 100644 --- a/ArchiSteamFarm/Web/Responses/BinaryResponse.cs +++ b/ArchiSteamFarm/Web/Responses/BinaryResponse.cs @@ -31,7 +31,12 @@ public sealed class BinaryResponse : BasicResponse { private readonly byte[]? Bytes; - public BinaryResponse(BasicResponse basicResponse, byte[] bytes) : this(basicResponse) => Bytes = bytes ?? throw new ArgumentNullException(nameof(bytes)); + public BinaryResponse(BasicResponse basicResponse, byte[] bytes) : this(basicResponse) { + ArgumentNullException.ThrowIfNull(basicResponse); + ArgumentNullException.ThrowIfNull(bytes); + + Bytes = bytes; + } public BinaryResponse(BasicResponse basicResponse) : base(basicResponse) => ArgumentNullException.ThrowIfNull(basicResponse); } diff --git a/ArchiSteamFarm/Web/Responses/HtmlDocumentResponse.cs b/ArchiSteamFarm/Web/Responses/HtmlDocumentResponse.cs index 14500a092..adc3c5856 100644 --- a/ArchiSteamFarm/Web/Responses/HtmlDocumentResponse.cs +++ b/ArchiSteamFarm/Web/Responses/HtmlDocumentResponse.cs @@ -33,7 +33,12 @@ public sealed class HtmlDocumentResponse : BasicResponse, IDisposable { public HtmlDocumentResponse(BasicResponse basicResponse) : base(basicResponse) => ArgumentNullException.ThrowIfNull(basicResponse); - private HtmlDocumentResponse(BasicResponse basicResponse, IDocument content) : this(basicResponse) => Content = content ?? throw new ArgumentNullException(nameof(content)); + private HtmlDocumentResponse(BasicResponse basicResponse, IDocument content) : this(basicResponse) { + ArgumentNullException.ThrowIfNull(basicResponse); + ArgumentNullException.ThrowIfNull(content); + + Content = content; + } public void Dispose() => Content?.Dispose(); diff --git a/ArchiSteamFarm/Web/Responses/ObjectResponse.cs b/ArchiSteamFarm/Web/Responses/ObjectResponse.cs index a5155c0b1..a63bf4668 100644 --- a/ArchiSteamFarm/Web/Responses/ObjectResponse.cs +++ b/ArchiSteamFarm/Web/Responses/ObjectResponse.cs @@ -28,7 +28,12 @@ public sealed class ObjectResponse : BasicResponse { [PublicAPI] public T? Content { get; } - public ObjectResponse(BasicResponse basicResponse, T content) : this(basicResponse) => Content = content ?? throw new ArgumentNullException(nameof(content)); + public ObjectResponse(BasicResponse basicResponse, T content) : this(basicResponse) { + ArgumentNullException.ThrowIfNull(basicResponse); + ArgumentNullException.ThrowIfNull(content); + + Content = content; + } public ObjectResponse(BasicResponse basicResponse) : base(basicResponse) => ArgumentNullException.ThrowIfNull(basicResponse); } diff --git a/ArchiSteamFarm/Web/Responses/StreamResponse.cs b/ArchiSteamFarm/Web/Responses/StreamResponse.cs index f33d6c22c..7ffd52919 100644 --- a/ArchiSteamFarm/Web/Responses/StreamResponse.cs +++ b/ArchiSteamFarm/Web/Responses/StreamResponse.cs @@ -36,10 +36,17 @@ public sealed class StreamResponse : BasicResponse, IAsyncDisposable, IDisposabl private readonly HttpResponseMessage ResponseMessage; - internal StreamResponse(HttpResponseMessage httpResponseMessage, Stream content) : this(httpResponseMessage) => Content = content ?? throw new ArgumentNullException(nameof(content)); + internal StreamResponse(HttpResponseMessage httpResponseMessage, Stream content) : this(httpResponseMessage) { + ArgumentNullException.ThrowIfNull(httpResponseMessage); + ArgumentNullException.ThrowIfNull(content); + + Content = content; + } internal StreamResponse(HttpResponseMessage httpResponseMessage) : base(httpResponseMessage) { - ResponseMessage = httpResponseMessage ?? throw new ArgumentNullException(nameof(httpResponseMessage)); + ArgumentNullException.ThrowIfNull(httpResponseMessage); + + ResponseMessage = httpResponseMessage; Length = httpResponseMessage.Content.Headers.ContentLength.GetValueOrDefault(); } diff --git a/ArchiSteamFarm/Web/WebBrowser.cs b/ArchiSteamFarm/Web/WebBrowser.cs index 61201f9b0..3513e6f8f 100644 --- a/ArchiSteamFarm/Web/WebBrowser.cs +++ b/ArchiSteamFarm/Web/WebBrowser.cs @@ -60,7 +60,9 @@ public sealed class WebBrowser : IDisposable { private readonly HttpClientHandler HttpClientHandler; internal WebBrowser(ArchiLogger archiLogger, IWebProxy? webProxy = null, bool extendedTimeout = false) { - ArchiLogger = archiLogger ?? throw new ArgumentNullException(nameof(archiLogger)); + ArgumentNullException.ThrowIfNull(archiLogger); + + ArchiLogger = archiLogger; HttpClientHandler = new HttpClientHandler { AllowAutoRedirect = false, // This must be false if we want to handle custom redirection schemes such as "steammobile://" @@ -126,14 +128,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlGetToBinary(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0, IProgress? progressReporter = null) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -236,14 +232,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlGetToHtmlDocument(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -302,14 +292,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task?> UrlGetToJsonObject(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -394,14 +378,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlGetToStream(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -445,14 +423,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlHead(Uri request, IReadOnlyCollection>? headers = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -495,14 +467,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlPost(Uri request, IReadOnlyCollection>? headers = null, T? data = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) where T : class { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -545,14 +511,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlPostToHtmlDocument(Uri request, IReadOnlyCollection>? headers = null, T? data = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) where T : class { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -611,14 +571,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task?> UrlPostToJsonObject(Uri request, IReadOnlyCollection>? headers = null, TData? data = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) where TData : class { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { @@ -703,14 +657,8 @@ public sealed class WebBrowser : IDisposable { [PublicAPI] public async Task UrlPostToStream(Uri request, IReadOnlyCollection>? headers = null, T? data = null, Uri? referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries, int rateLimitingDelay = 0) where T : class { ArgumentNullException.ThrowIfNull(request); - - if (maxTries == 0) { - throw new ArgumentOutOfRangeException(nameof(maxTries)); - } - - if (rateLimitingDelay < 0) { - throw new ArgumentOutOfRangeException(nameof(rateLimitingDelay)); - } + ArgumentOutOfRangeException.ThrowIfZero(maxTries); + ArgumentOutOfRangeException.ThrowIfNegative(rateLimitingDelay); for (byte i = 0; i < maxTries; i++) { if ((i > 0) && (rateLimitingDelay > 0)) { diff --git a/ArchiSteamFarm/overlay/variant-base/linux/ArchiSteamFarm@.service b/ArchiSteamFarm/overlay/variant-base/linux/ArchiSteamFarm@.service index 80342d0cf..bd3f5f890 100644 --- a/ArchiSteamFarm/overlay/variant-base/linux/ArchiSteamFarm@.service +++ b/ArchiSteamFarm/overlay/variant-base/linux/ArchiSteamFarm@.service @@ -34,16 +34,12 @@ RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes +SecureBits=noroot-locked SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged UMask=0077 -# TODO: Requires systemd v247+ due to https://github.com/systemd/systemd/issues/16666 and https://github.com/JustArchiNET/ArchiSteamFarm/issues/2739 -# Since we don't want to enforce OS upgrade for everybody just yet, it's commented out for now -# We'll likely enforce it when .NET switches to Debian 11+ requirement -#SecureBits=noroot-locked -#SystemCallFilter=@system-service -#SystemCallFilter=~@privileged - [Unit] After=network.target Description=ArchiSteamFarm Service (on %I) diff --git a/ArchiSteamFarm/overlay/variant-specific/generic-netf/ArchiSteamFarm@.service b/ArchiSteamFarm/overlay/variant-specific/generic-netf/ArchiSteamFarm@.service index f8fda0b80..189d3e89e 100644 --- a/ArchiSteamFarm/overlay/variant-specific/generic-netf/ArchiSteamFarm@.service +++ b/ArchiSteamFarm/overlay/variant-specific/generic-netf/ArchiSteamFarm@.service @@ -34,16 +34,12 @@ RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes +SecureBits=noroot-locked SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged UMask=0077 -# TODO: Requires systemd v247+ due to https://github.com/systemd/systemd/issues/16666 and https://github.com/JustArchiNET/ArchiSteamFarm/issues/2739 -# Since we don't want to enforce OS upgrade for everybody just yet, it's commented out for now -# We'll likely enforce it when .NET switches to Debian 11+ requirement -#SecureBits=noroot-locked -#SystemCallFilter=@system-service -#SystemCallFilter=~@privileged - [Unit] After=network.target Description=ArchiSteamFarm Service (on %I) diff --git a/ArchiSteamFarm/overlay/variant-specific/generic/ArchiSteamFarm@.service b/ArchiSteamFarm/overlay/variant-specific/generic/ArchiSteamFarm@.service index 215b7fc36..6669ddb86 100644 --- a/ArchiSteamFarm/overlay/variant-specific/generic/ArchiSteamFarm@.service +++ b/ArchiSteamFarm/overlay/variant-specific/generic/ArchiSteamFarm@.service @@ -34,16 +34,12 @@ RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX RestrictNamespaces=yes RestrictRealtime=yes RestrictSUIDSGID=yes +SecureBits=noroot-locked SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged UMask=0077 -# TODO: Requires systemd v247+ due to https://github.com/systemd/systemd/issues/16666 and https://github.com/JustArchiNET/ArchiSteamFarm/issues/2739 -# Since we don't want to enforce OS upgrade for everybody just yet, it's commented out for now -# We'll likely enforce it when .NET switches to Debian 11+ requirement -#SecureBits=noroot-locked -#SystemCallFilter=@system-service -#SystemCallFilter=~@privileged - [Unit] After=network.target Description=ArchiSteamFarm Service (on %I) diff --git a/Directory.Build.props b/Directory.Build.props index 9c7432294..79b644648 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -29,7 +29,7 @@ $(PackageProjectUrl).git LatestMajor linux-arm;linux-arm64;linux-x64;osx-arm64;osx-x64;win-arm64;win-x64 - net7.0 + net8.0 true @@ -46,8 +46,11 @@ + + + @@ -91,6 +94,9 @@ true CS8002,IL2026,IL2057,IL2072,IL2075,IL2104,IL3000 + + + $(WarningsNotAsErrors),CA1863 diff --git a/Dockerfile b/Dockerfile index 1e8038b68..637abfd68 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,14 +10,14 @@ RUN set -eu; \ npm ci --no-progress; \ npm run deploy --no-progress -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0${IMAGESUFFIX} AS build-dotnet +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0${IMAGESUFFIX} AS build-dotnet ARG CONFIGURATION=Release ARG STEAM_TOKEN_DUMPER_TOKEN ARG TARGETARCH ARG TARGETOS ENV DOTNET_CLI_TELEMETRY_OPTOUT true ENV DOTNET_NOLOGO true -ENV NET_CORE_VERSION net7.0 +ENV NET_CORE_VERSION net8.0 ENV PLUGINS ArchiSteamFarm.OfficialPlugins.ItemsMatcher ArchiSteamFarm.OfficialPlugins.MobileAuthenticator ArchiSteamFarm.OfficialPlugins.SteamTokenDumper WORKDIR /app COPY --from=build-node /app/ASF-ui/dist ASF-ui/dist @@ -55,7 +55,7 @@ RUN set -eu; \ dotnet publish "$plugin" -c "$CONFIGURATION" -f "$NET_CORE_VERSION" -o "out/result/plugins/$plugin" -p:ASFVariant=docker -p:ContinuousIntegrationBuild=true -p:UseAppHost=false -r "$asf_variant" --nologo --no-self-contained; \ done -FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/aspnet:7.0${IMAGESUFFIX} AS runtime +FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/aspnet:8.0${IMAGESUFFIX} AS runtime ENV ASF_USER asf ENV ASPNETCORE_URLS= ENV DOTNET_CLI_TELEMETRY_OPTOUT true diff --git a/Dockerfile.Service b/Dockerfile.Service index c8b063f3b..e57161ec0 100644 --- a/Dockerfile.Service +++ b/Dockerfile.Service @@ -10,14 +10,14 @@ RUN set -eu; \ npm ci --no-progress; \ npm run deploy --no-progress -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0${IMAGESUFFIX} AS build-dotnet +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0${IMAGESUFFIX} AS build-dotnet ARG CONFIGURATION=Release ARG STEAM_TOKEN_DUMPER_TOKEN ARG TARGETARCH ARG TARGETOS ENV DOTNET_CLI_TELEMETRY_OPTOUT true ENV DOTNET_NOLOGO true -ENV NET_CORE_VERSION net7.0 +ENV NET_CORE_VERSION net8.0 ENV PLUGINS ArchiSteamFarm.OfficialPlugins.ItemsMatcher ArchiSteamFarm.OfficialPlugins.MobileAuthenticator ArchiSteamFarm.OfficialPlugins.SteamTokenDumper WORKDIR /app COPY --from=build-node /app/ASF-ui/dist ASF-ui/dist @@ -55,7 +55,7 @@ RUN set -eu; \ dotnet publish "$plugin" -c "$CONFIGURATION" -f "$NET_CORE_VERSION" -o "out/result/plugins/$plugin" "-p:ASFVariant=${asf_variant}" -p:ContinuousIntegrationBuild=true -p:UseAppHost=false -r "$asf_variant" --nologo --no-self-contained; \ done -FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/runtime-deps:7.0${IMAGESUFFIX} AS runtime +FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/runtime-deps:8.0${IMAGESUFFIX} AS runtime ENV ASF_USER asf ENV ASPNETCORE_URLS= ENV DOTNET_CLI_TELEMETRY_OPTOUT true diff --git a/cc.sh b/cc.sh index be364a131..fa6f5de0f 100755 --- a/cc.sh +++ b/cc.sh @@ -1,7 +1,7 @@ #!/usr/bin/env sh set -eu -TARGET_FRAMEWORK="net7.0" +TARGET_FRAMEWORK="net8.0" MAIN_PROJECT="ArchiSteamFarm" STEAM_TOKEN_DUMPER_NAME="${MAIN_PROJECT}.OfficialPlugins.SteamTokenDumper"