From 067293eeb54dea97760aba9b5213844c8df95acb Mon Sep 17 00:00:00 2001 From: JustArchi Date: Fri, 27 Sep 2019 20:43:11 +0200 Subject: [PATCH] Start with .NET Core 3.0 code enhancements --- ArchiSteamFarm/ASF.cs | 8 +- ArchiSteamFarm/ArchiWebHandler.cs | 174 +++++++------- ArchiSteamFarm/Bot.cs | 77 +++--- .../CMsgs/CMsgClientAcknowledgeClanInvite.cs | 16 +- ArchiSteamFarm/GitHub.cs | 30 +-- .../IPC/Controllers/Api/NLogController.cs | 52 ++--- ArchiSteamFarm/Plugins/PluginsCore.cs | 6 +- ArchiSteamFarm/RuntimeCompatibility.cs | 6 +- ArchiSteamFarm/WebBrowser.cs | 219 +++++++++--------- 9 files changed, 295 insertions(+), 293 deletions(-) diff --git a/ArchiSteamFarm/ASF.cs b/ArchiSteamFarm/ASF.cs index 52c17e462..a712b3c5e 100644 --- a/ArchiSteamFarm/ASF.cs +++ b/ArchiSteamFarm/ASF.cs @@ -259,10 +259,10 @@ namespace ArchiSteamFarm { } try { - using (ZipArchive zipArchive = new ZipArchive(new MemoryStream(response.Content))) { - if (!UpdateFromArchive(zipArchive, SharedInfo.HomeDirectory)) { - ArchiLogger.LogGenericError(Strings.WarningFailed); - } + using ZipArchive zipArchive = new ZipArchive(new MemoryStream(response.Content)); + + if (!UpdateFromArchive(zipArchive, SharedInfo.HomeDirectory)) { + ArchiLogger.LogGenericError(Strings.WarningFailed); } } catch (Exception e) { ArchiLogger.LogGenericException(e); diff --git a/ArchiSteamFarm/ArchiWebHandler.cs b/ArchiSteamFarm/ArchiWebHandler.cs index 0ef92b4a8..2778749dd 100644 --- a/ArchiSteamFarm/ArchiWebHandler.cs +++ b/ArchiSteamFarm/ArchiWebHandler.cs @@ -304,27 +304,27 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iPlayerService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IPlayerService)) { - iPlayerService.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iPlayerService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IPlayerService); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iPlayerService.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iPlayerService.CallAsync( - HttpMethod.Get, "GetOwnedGames", args: new Dictionary(3, StringComparer.Ordinal) { + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iPlayerService.CallAsync( + HttpMethod.Get, "GetOwnedGames", args: new Dictionary(3, StringComparer.Ordinal) { { "include_appinfo", 1 }, { "key", steamApiKey }, { "steamid", steamID } - } - ).ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + } + ).ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } @@ -1356,26 +1356,26 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService)) { - iEconService.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iEconService.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iEconService.CallAsync( - HttpMethod.Post, "DeclineTradeOffer", args: new Dictionary(2, StringComparer.Ordinal) { + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iEconService.CallAsync( + HttpMethod.Post, "DeclineTradeOffer", args: new Dictionary(2, StringComparer.Ordinal) { { "key", steamApiKey }, { "tradeofferid", tradeID } - } - ).ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + } + ).ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } @@ -1414,29 +1414,29 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService)) { - iEconService.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iEconService.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iEconService.CallAsync( - HttpMethod.Get, "GetTradeOffers", args: new Dictionary(5, StringComparer.Ordinal) { + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iEconService.CallAsync( + HttpMethod.Get, "GetTradeOffers", args: new Dictionary(5, StringComparer.Ordinal) { { "active_only", 1 }, { "get_descriptions", 1 }, { "get_received_offers", 1 }, { "key", steamApiKey }, { "time_historical_cutoff", uint.MaxValue } - } - ).ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + } + ).ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } @@ -1570,21 +1570,21 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iSteamApps = Bot.SteamConfiguration.GetAsyncWebAPIInterface(ISteamApps)) { - iSteamApps.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iSteamApps = Bot.SteamConfiguration.GetAsyncWebAPIInterface(ISteamApps); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iSteamApps.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iSteamApps.CallAsync(HttpMethod.Get, "GetAppList", 2).ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iSteamApps.CallAsync(HttpMethod.Get, "GetAppList", 2).ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } @@ -1779,21 +1779,21 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iTwoFactorService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(ITwoFactorService)) { - iTwoFactorService.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iTwoFactorService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(ITwoFactorService); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iTwoFactorService.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iTwoFactorService.CallAsync(HttpMethod.Post, "QueryTime").ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iTwoFactorService.CallAsync(HttpMethod.Post, "QueryTime").ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } @@ -1897,21 +1897,21 @@ namespace ArchiSteamFarm { KeyValue response = null; for (byte i = 0; (i < WebBrowser.MaxTries) && (response == null); i++) { - using (WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService)) { - iEconService.Timeout = WebBrowser.Timeout; + using WebAPI.AsyncInterface iEconService = Bot.SteamConfiguration.GetAsyncWebAPIInterface(IEconService); - try { - response = await WebLimitRequest( - WebAPI.DefaultBaseAddress.Host, + iEconService.Timeout = WebBrowser.Timeout; - // ReSharper disable once AccessToDisposedClosure - async () => await iEconService.CallAsync(HttpMethod.Get, "GetTradeHoldDurations", args: arguments).ConfigureAwait(false) - ).ConfigureAwait(false); - } catch (TaskCanceledException e) { - Bot.ArchiLogger.LogGenericDebuggingException(e); - } catch (Exception e) { - Bot.ArchiLogger.LogGenericWarningException(e); - } + try { + response = await WebLimitRequest( + WebAPI.DefaultBaseAddress.Host, + + // ReSharper disable once AccessToDisposedClosure + async () => await iEconService.CallAsync(HttpMethod.Get, "GetTradeHoldDurations", args: arguments).ConfigureAwait(false) + ).ConfigureAwait(false); + } catch (TaskCanceledException e) { + Bot.ArchiLogger.LogGenericDebuggingException(e); + } catch (Exception e) { + Bot.ArchiLogger.LogGenericWarningException(e); } } diff --git a/ArchiSteamFarm/Bot.cs b/ArchiSteamFarm/Bot.cs index bdf41c783..d3480cff1 100755 --- a/ArchiSteamFarm/Bot.cs +++ b/ArchiSteamFarm/Bot.cs @@ -448,12 +448,11 @@ namespace ArchiSteamFarm { return true; } - switch (permission) { - case BotConfig.EPermission.FamilySharing when SteamFamilySharingIDs.Contains(steamID): - return true; - default: - return BotConfig.SteamUserPermissions.TryGetValue(steamID, out BotConfig.EPermission realPermission) && (realPermission >= permission); - } + return permission switch + { + BotConfig.EPermission.FamilySharing when SteamFamilySharingIDs.Contains(steamID) => true, + _ => BotConfig.SteamUserPermissions.TryGetValue(steamID, out BotConfig.EPermission realPermission) && (realPermission >= permission), + }; } internal void AddGamesToRedeemInBackground(IOrderedDictionary gamesToRedeemInBackground) { @@ -1586,33 +1585,33 @@ namespace ArchiSteamFarm { Dictionary keys = new Dictionary(StringComparer.Ordinal); try { - using (StreamReader reader = new StreamReader(filePath)) { - string line; + using StreamReader reader = new StreamReader(filePath); - while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { - if (line.Length == 0) { - continue; - } + string line; - string[] parsedArgs = line.Split(DefaultBackgroundKeysRedeemerSeparator, StringSplitOptions.RemoveEmptyEntries); - - if (parsedArgs.Length < 3) { - ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, line)); - - continue; - } - - string key = parsedArgs[parsedArgs.Length - 1]; - - if (!Utilities.IsValidCdKey(key)) { - ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, key)); - - continue; - } - - string name = parsedArgs[0]; - keys[key] = name; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { + if (line.Length == 0) { + continue; } + + string[] parsedArgs = line.Split(DefaultBackgroundKeysRedeemerSeparator, StringSplitOptions.RemoveEmptyEntries); + + if (parsedArgs.Length < 3) { + ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, line)); + + continue; + } + + string key = parsedArgs[parsedArgs.Length - 1]; + + if (!Utilities.IsValidCdKey(key)) { + ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorIsInvalid, key)); + + continue; + } + + string name = parsedArgs[0]; + keys[key] = name; } } catch (Exception e) { ArchiLogger.LogGenericException(e); @@ -2574,18 +2573,18 @@ namespace ArchiSteamFarm { byte[] sentryHash; try { - using (FileStream fileStream = File.Open(sentryFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { - fileStream.Seek(callback.Offset, SeekOrigin.Begin); + using FileStream fileStream = File.Open(sentryFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); - await fileStream.WriteAsync(callback.Data, 0, callback.BytesToWrite).ConfigureAwait(false); + fileStream.Seek(callback.Offset, SeekOrigin.Begin); - fileSize = fileStream.Length; - fileStream.Seek(0, SeekOrigin.Begin); + await fileStream.WriteAsync(callback.Data, 0, callback.BytesToWrite).ConfigureAwait(false); - using (SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider()) { - sentryHash = sha.ComputeHash(fileStream); - } - } + fileSize = fileStream.Length; + fileStream.Seek(0, SeekOrigin.Begin); + + using SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); + + sentryHash = sha.ComputeHash(fileStream); } catch (Exception e) { ArchiLogger.LogGenericException(e); diff --git a/ArchiSteamFarm/CMsgs/CMsgClientAcknowledgeClanInvite.cs b/ArchiSteamFarm/CMsgs/CMsgClientAcknowledgeClanInvite.cs index 070865b98..9658faa6b 100644 --- a/ArchiSteamFarm/CMsgs/CMsgClientAcknowledgeClanInvite.cs +++ b/ArchiSteamFarm/CMsgs/CMsgClientAcknowledgeClanInvite.cs @@ -36,10 +36,10 @@ namespace ArchiSteamFarm.CMsgs { return; } - using (BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, true)) { - ClanID = binaryReader.ReadUInt64(); - AcceptInvite = binaryReader.ReadBoolean(); - } + using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, true); + + ClanID = binaryReader.ReadUInt64(); + AcceptInvite = binaryReader.ReadBoolean(); } EMsg ISteamSerializableMessage.GetEMsg() => EMsg.ClientAcknowledgeClanInvite; @@ -51,10 +51,10 @@ namespace ArchiSteamFarm.CMsgs { return; } - using (BinaryWriter binaryWriter = new BinaryWriter(stream, Encoding.UTF8, true)) { - binaryWriter.Write(ClanID); - binaryWriter.Write(AcceptInvite); - } + using BinaryWriter binaryWriter = new BinaryWriter(stream, Encoding.UTF8, true); + + binaryWriter.Write(ClanID); + binaryWriter.Write(AcceptInvite); } } } diff --git a/ArchiSteamFarm/GitHub.cs b/ArchiSteamFarm/GitHub.cs index 9f4eff07b..b60641dd3 100644 --- a/ArchiSteamFarm/GitHub.cs +++ b/ArchiSteamFarm/GitHub.cs @@ -129,13 +129,13 @@ namespace ArchiSteamFarm { return null; } - using (StringWriter writer = new StringWriter()) { - HtmlRenderer renderer = new HtmlRenderer(writer); - renderer.Render(Changelog); - writer.Flush(); + using StringWriter writer = new StringWriter(); - return BackingChangelogHTML = writer.ToString(); - } + HtmlRenderer renderer = new HtmlRenderer(writer); + renderer.Render(Changelog); + writer.Flush(); + + return BackingChangelogHTML = writer.ToString(); } } @@ -151,17 +151,17 @@ namespace ArchiSteamFarm { return null; } - using (StringWriter writer = new StringWriter()) { - HtmlRenderer renderer = new HtmlRenderer(writer) { - EnableHtmlForBlock = false, - EnableHtmlForInline = false - }; + using StringWriter writer = new StringWriter(); - renderer.Render(Changelog); - writer.Flush(); + HtmlRenderer renderer = new HtmlRenderer(writer) { + EnableHtmlForBlock = false, + EnableHtmlForInline = false + }; - return BackingChangelogPlainText = writer.ToString(); - } + renderer.Render(Changelog); + writer.Flush(); + + return BackingChangelogPlainText = writer.ToString(); } } diff --git a/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs b/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs index a03ae30fb..1388fa5d5 100644 --- a/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs +++ b/ArchiSteamFarm/IPC/Controllers/Api/NLogController.cs @@ -55,40 +55,40 @@ namespace ArchiSteamFarm.IPC.Controllers.Api { // From now on we can return only EmptyResult as the response stream is already being used by existing websocket connection try { - using (WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false)) { - SemaphoreSlim sendSemaphore = new SemaphoreSlim(1, 1); + using WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); - if (!ActiveLogWebSockets.TryAdd(webSocket, sendSemaphore)) { - sendSemaphore.Dispose(); + SemaphoreSlim sendSemaphore = new SemaphoreSlim(1, 1); - return new EmptyResult(); + if (!ActiveLogWebSockets.TryAdd(webSocket, sendSemaphore)) { + sendSemaphore.Dispose(); + + return new EmptyResult(); + } + + try { + // Push initial history if available + if (ArchiKestrel.HistoryTarget != null) { + // ReSharper disable once AccessToDisposedClosure - we're waiting for completion with Task.WhenAll(), we're not going to exit using block + await Task.WhenAll(ArchiKestrel.HistoryTarget.ArchivedMessages.Select(archivedMessage => PostLoggedMessageUpdate(webSocket, sendSemaphore, archivedMessage))).ConfigureAwait(false); } - try { - // Push initial history if available - if (ArchiKestrel.HistoryTarget != null) { - // ReSharper disable once AccessToDisposedClosure - we're waiting for completion with Task.WhenAll(), we're not going to exit using block - await Task.WhenAll(ArchiKestrel.HistoryTarget.ArchivedMessages.Select(archivedMessage => PostLoggedMessageUpdate(webSocket, sendSemaphore, archivedMessage))).ConfigureAwait(false); - } + while (webSocket.State == WebSocketState.Open) { + WebSocketReceiveResult result = await webSocket.ReceiveAsync(new byte[0], CancellationToken.None).ConfigureAwait(false); - while (webSocket.State == WebSocketState.Open) { - WebSocketReceiveResult result = await webSocket.ReceiveAsync(new byte[0], CancellationToken.None).ConfigureAwait(false); - - if (result.MessageType != WebSocketMessageType.Close) { - await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "You're not supposed to be sending any message but Close!", CancellationToken.None).ConfigureAwait(false); - - break; - } - - await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false); + if (result.MessageType != WebSocketMessageType.Close) { + await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "You're not supposed to be sending any message but Close!", CancellationToken.None).ConfigureAwait(false); break; } - } finally { - if (ActiveLogWebSockets.TryRemove(webSocket, out SemaphoreSlim closedSemaphore)) { - await closedSemaphore.WaitAsync().ConfigureAwait(false); // Ensure that our semaphore is truly closed by now - closedSemaphore.Dispose(); - } + + await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false); + + break; + } + } finally { + if (ActiveLogWebSockets.TryRemove(webSocket, out SemaphoreSlim closedSemaphore)) { + await closedSemaphore.WaitAsync().ConfigureAwait(false); // Ensure that our semaphore is truly closed by now + closedSemaphore.Dispose(); } } } catch (WebSocketException e) { diff --git a/ArchiSteamFarm/Plugins/PluginsCore.cs b/ArchiSteamFarm/Plugins/PluginsCore.cs index b0bfb0e8f..59a14daec 100644 --- a/ArchiSteamFarm/Plugins/PluginsCore.cs +++ b/ArchiSteamFarm/Plugins/PluginsCore.cs @@ -86,9 +86,9 @@ namespace ArchiSteamFarm.Plugins { HashSet activePlugins; try { - using (CompositionHost container = configuration.CreateContainer()) { - activePlugins = container.GetExports().ToHashSet(); - } + using CompositionHost container = configuration.CreateContainer(); + + activePlugins = container.GetExports().ToHashSet(); } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); diff --git a/ArchiSteamFarm/RuntimeCompatibility.cs b/ArchiSteamFarm/RuntimeCompatibility.cs index d572cbb8c..89163d75f 100644 --- a/ArchiSteamFarm/RuntimeCompatibility.cs +++ b/ArchiSteamFarm/RuntimeCompatibility.cs @@ -48,9 +48,9 @@ namespace ArchiSteamFarm { } #endif - using (Process process = Process.GetCurrentProcess()) { - return process.StartTime; - } + using Process process = Process.GetCurrentProcess(); + + return process.StartTime; } } diff --git a/ArchiSteamFarm/WebBrowser.cs b/ArchiSteamFarm/WebBrowser.cs index 1ffb5951a..1120ce276 100644 --- a/ArchiSteamFarm/WebBrowser.cs +++ b/ArchiSteamFarm/WebBrowser.cs @@ -81,6 +81,9 @@ namespace ArchiSteamFarm { [PublicAPI] public HttpClient GenerateDisposableHttpClient(bool extendedTimeout = false) { HttpClient result = new HttpClient(HttpClientHandler, false) { +#if !NETFRAMEWORK + DefaultRequestVersion = new Version(2, 0), +#endif Timeout = TimeSpan.FromSeconds(extendedTimeout ? ExtendedTimeoutMultiplier * ASF.GlobalConfig.ConnectionTimeout : ASF.GlobalConfig.ConnectionTimeout) }; @@ -225,21 +228,21 @@ namespace ArchiSteamFarm { BasicResponse result = null; for (byte i = 0; i < maxTries; i++) { - using (HttpResponseMessage response = await InternalHead(request, referer).ConfigureAwait(false)) { - if (response == null) { - continue; - } + using HttpResponseMessage response = await InternalHead(request, referer).ConfigureAwait(false); - if (response.StatusCode.IsClientErrorCode()) { - if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { - result = new BasicResponse(response); - } - - break; - } - - return new BasicResponse(response); + if (response == null) { + continue; } + + if (response.StatusCode.IsClientErrorCode()) { + if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { + result = new BasicResponse(response); + } + + break; + } + + return new BasicResponse(response); } if (maxTries > 1) { @@ -262,21 +265,21 @@ namespace ArchiSteamFarm { BasicResponse result = null; for (byte i = 0; i < maxTries; i++) { - using (HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false)) { - if (response == null) { - continue; - } + using HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false); - if (response.StatusCode.IsClientErrorCode()) { - if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { - result = new BasicResponse(response); - } - - break; - } - - return new BasicResponse(response); + if (response == null) { + continue; } + + if (response.StatusCode.IsClientErrorCode()) { + if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { + result = new BasicResponse(response); + } + + break; + } + + return new BasicResponse(response); } if (maxTries > 1) { @@ -399,64 +402,64 @@ namespace ArchiSteamFarm { const byte printPercentage = 10; const byte maxBatches = 99 / printPercentage; - using (HttpResponseMessage response = await InternalGet(request, referer, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) { - if (response == null) { - continue; - } + using HttpResponseMessage response = await InternalGet(request, referer, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); - if (response.StatusCode.IsClientErrorCode()) { - if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { - result = new BinaryResponse(response); - } - - break; - } - - ArchiLogger.LogGenericDebug("0%..."); - - uint contentLength = (uint) response.Content.Headers.ContentLength.GetValueOrDefault(); - - using (MemoryStream ms = new MemoryStream((int) contentLength)) { - try { - using (Stream contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { - byte batch = 0; - uint readThisBatch = 0; - byte[] buffer = new byte[8192]; // This is HttpClient's buffer, using more doesn't make sense - - while (contentStream.CanRead) { - int read = await contentStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - - if (read == 0) { - break; - } - - await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false); - - if ((contentLength == 0) || (batch >= maxBatches)) { - continue; - } - - readThisBatch += (uint) read; - - if (readThisBatch < contentLength / printPercentage) { - continue; - } - - readThisBatch -= contentLength / printPercentage; - ArchiLogger.LogGenericDebug((++batch * printPercentage) + "%..."); - } - } - } catch (Exception e) { - ArchiLogger.LogGenericDebuggingException(e); - - return null; - } - - ArchiLogger.LogGenericDebug("100%"); - - return new BinaryResponse(response, ms.ToArray()); - } + if (response == null) { + continue; } + + if (response.StatusCode.IsClientErrorCode()) { + if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { + result = new BinaryResponse(response); + } + + break; + } + + ArchiLogger.LogGenericDebug("0%..."); + + uint contentLength = (uint) response.Content.Headers.ContentLength.GetValueOrDefault(); + + using MemoryStream ms = new MemoryStream((int) contentLength); + + try { + using Stream contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + + byte batch = 0; + uint readThisBatch = 0; + byte[] buffer = new byte[8192]; // This is HttpClient's buffer, using more doesn't make sense + + while (contentStream.CanRead) { + int read = await contentStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); + + if (read == 0) { + break; + } + + await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false); + + if ((contentLength == 0) || (batch >= maxBatches)) { + continue; + } + + readThisBatch += (uint) read; + + if (readThisBatch < contentLength / printPercentage) { + continue; + } + + readThisBatch -= contentLength / printPercentage; + ArchiLogger.LogGenericDebug((++batch * printPercentage) + "%..."); + } + } catch (Exception e) { + ArchiLogger.LogGenericDebuggingException(e); + + return null; + } + + ArchiLogger.LogGenericDebug("100%"); + + return new BinaryResponse(response, ms.ToArray()); } if (maxTries > 1) { @@ -478,21 +481,21 @@ namespace ArchiSteamFarm { StringResponse result = null; for (byte i = 0; i < maxTries; i++) { - using (HttpResponseMessage response = await InternalGet(request, referer).ConfigureAwait(false)) { - if (response == null) { - continue; - } + using HttpResponseMessage response = await InternalGet(request, referer).ConfigureAwait(false); - if (response.StatusCode.IsClientErrorCode()) { - if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { - result = new StringResponse(response); - } - - break; - } - - return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false)); + if (response == null) { + continue; } + + if (response.StatusCode.IsClientErrorCode()) { + if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { + result = new StringResponse(response); + } + + break; + } + + return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false)); } if (maxTries > 1) { @@ -647,21 +650,21 @@ namespace ArchiSteamFarm { StringResponse result = null; for (byte i = 0; i < maxTries; i++) { - using (HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false)) { - if (response == null) { - continue; - } + using HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false); - if (response.StatusCode.IsClientErrorCode()) { - if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { - result = new StringResponse(response); - } - - break; - } - - return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false)); + if (response == null) { + continue; } + + if (response.StatusCode.IsClientErrorCode()) { + if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { + result = new StringResponse(response); + } + + break; + } + + return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false)); } if (maxTries > 1) {