From 3754ed4b900a29d88bb70cbd72faca79f745c3e5 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 17 Nov 2022 10:25:06 +0100 Subject: [PATCH 01/18] cleanup string.Format --- .../Common/WebRequestPSCmdlet.Common.cs | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 85932f7eb86..d9ede19f892 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1268,8 +1268,11 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } catch (UnauthorizedAccessException) { - string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, - _originalFilePath); + string msg = string.Format( + CultureInfo.InvariantCulture, + WebCmdletStrings.AccessDenied, + _originalFilePath); + throw new UnauthorizedAccessException(msg); } } @@ -1436,6 +1439,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM requestWithoutRange.Version, requestWithoutRange.Method, requestContentLength); + WriteVerbose(reqVerboseMsg); return GetResponse(client, requestWithoutRange, keepAuthorization); @@ -1510,9 +1514,11 @@ protected override void ProcessRecord() { if (followedRelLink > 0) { - string linkVerboseMsg = string.Format(CultureInfo.CurrentCulture, + string linkVerboseMsg = string.Format( + CultureInfo.CurrentCulture, WebCmdletStrings.FollowingRelLinkVerboseMsg, uri.AbsoluteUri); + WriteVerbose(linkVerboseMsg); } @@ -1537,10 +1543,12 @@ protected override void ProcessRecord() HttpResponseMessage response = GetResponse(client, request, keepAuthorization); string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format(CultureInfo.CurrentCulture, + string respVerboseMsg = string.Format( + CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, response.Content.Headers.ContentLength, contentType); + WriteVerbose(respVerboseMsg); bool _isSuccess = response.IsSuccessStatusCode; @@ -1553,15 +1561,23 @@ protected override void ProcessRecord() response.Content.Headers.ContentRange.Length == _resumeFileSize) { _isSuccess = true; - WriteVerbose(string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.OutFileWritingSkipped, OutFile)); + WriteVerbose(string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.OutFileWritingSkipped, + OutFile)); + // Disable writing to the OutFile. OutFile = null; } if (ShouldCheckHttpStatus && !_isSuccess) { - string message = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.ResponseStatusCodeFailure, - (int)response.StatusCode, response.ReasonPhrase); + string message = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.ResponseStatusCodeFailure, + (int)response.StatusCode, + response.ReasonPhrase); + HttpResponseException httpEx = new(message, response); ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); string detailMsg = string.Empty; From 39730a306bb2cbb6c0a8b4e41392e00ae0c09c1e Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 17 Nov 2022 10:27:00 +0100 Subject: [PATCH 02/18] cleanup && --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index d9ede19f892..4b446cb47a5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1272,7 +1272,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, _originalFilePath); - + throw new UnauthorizedAccessException(msg); } } @@ -1498,13 +1498,10 @@ protected override void ProcessRecord() // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession != null - && - WebSession.Headers != null - && - PreserveAuthorizationOnRedirect.IsPresent - && - WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + bool keepAuthorization = WebSession != null && + WebSession.Headers != null && + PreserveAuthorizationOnRedirect.IsPresent && + WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); using (HttpClient client = GetHttpClient(keepAuthorization)) { From 14c6ead84525db19e41095704b0dabcc6ce7c833 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:00:58 +0100 Subject: [PATCH 03/18] remove empty comments --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 4b446cb47a5..2812a6b1ee2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -592,9 +592,7 @@ internal virtual void PrepareSession() vi.Set(SessionVariable, WebSession); } - // // handle credentials - // if (Credential != null && Authentication == WebAuthenticationType.None) { // get the relevant NetworkCredential @@ -637,9 +635,7 @@ internal virtual void PrepareSession() WebSession.AddCertificate(Certificate); } - // // handle the user agent - // if (UserAgent != null) { // store the UserAgent string From 6f9d9bfe126460d919286ec84be00647bac92262 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:08:48 +0100 Subject: [PATCH 04/18] GetValidationError single line --- .../Common/WebRequestPSCmdlet.Common.cs | 57 +++++++------------ 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 2812a6b1ee2..ae0dcc15c84 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -412,95 +412,82 @@ internal virtual void ValidateParameters() // sessions if ((WebSession != null) && (SessionVariable != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, - "WebCmdletSessionConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } // Authentication if (UseDefaultCredentials && (Authentication != WebAuthenticationType.None)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, - "WebCmdletAuthenticationConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, - "WebCmdletAuthenticationTokenConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, - "WebCmdletAuthenticationCredentialNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, - "WebCmdletAuthenticationTokenNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https")) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } // credentials if (UseDefaultCredentials && (Credential != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, - "WebCmdletCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server if (ProxyUseDefaultCredentials && (ProxyCredential != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, - "WebCmdletProxyCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, - "WebCmdletProxyUriNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } // request body content if ((Body != null) && (InFile != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, - "WebCmdletBodyConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } if ((Body != null) && (Form != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, - "WebCmdletBodyFormConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } if ((InFile != null) && (Form != null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, - "WebCmdletFormInFileConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); ThrowTerminatingError(error); } @@ -516,27 +503,23 @@ internal virtual void ValidateParameters() if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, - "WebCmdletInFileNotFilesystemPathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile); } else { if (providerPaths.Count > 1) { - errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, - "WebCmdletInFileMultiplePathsResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } else if (providerPaths.Count == 0) { - errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, - "WebCmdletInFileNoPathResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } else { if (Directory.Exists(providerPaths[0])) { - errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, - "WebCmdletInFileNotFilePathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); } _originalFilePath = InFile; @@ -566,16 +549,14 @@ internal virtual void ValidateParameters() // output ?? if (PassThru && (OutFile == null)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(PassThru)); + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); } // Resume requires OutFile. if (Resume.IsPresent && OutFile == null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(Resume)); + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); ThrowTerminatingError(error); } } From a47291208f5212f1613679da1730215fac917858 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:21:54 +0100 Subject: [PATCH 05/18] Remove redundant brackets --- .../Common/WebRequestPSCmdlet.Common.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index ae0dcc15c84..c03d5b5d402 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -410,82 +410,82 @@ public virtual string CustomMethod internal virtual void ValidateParameters() { // sessions - if ((WebSession != null) && (SessionVariable != null)) + if (WebSession != null && SessionVariable != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } // Authentication - if (UseDefaultCredentials && (Authentication != WebAuthenticationType.None)) + if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } - if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) + if (Authentication != WebAuthenticationType.None && Token != null && Credential != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) + if (Authentication == WebAuthenticationType.Basic && Credential == null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token == null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && Uri.Scheme != "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } // credentials - if (UseDefaultCredentials && (Credential != null)) + if (UseDefaultCredentials && Credential != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server - if (ProxyUseDefaultCredentials && (ProxyCredential != null)) + if (ProxyUseDefaultCredentials && ProxyCredential != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) + else if (Proxy == null && (ProxyCredential != null || ProxyUseDefaultCredentials)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } // request body content - if ((Body != null) && (InFile != null)) + if (Body != null && InFile != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } - if ((Body != null) && (Form != null)) + if (Body != null && Form != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } - if ((InFile != null) && (Form != null)) + if (InFile != null && Form != null) { ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); ThrowTerminatingError(error); @@ -547,7 +547,7 @@ internal virtual void ValidateParameters() } // output ?? - if (PassThru && (OutFile == null)) + if (PassThru && OutFile == null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); @@ -715,9 +715,9 @@ private Uri PrepareUri(Uri uri) // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if ((bodyAsDictionary != null) + if (bodyAsDictionary != null && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) - || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) + || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { UriBuilder uriBuilder = new(uri); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) @@ -1330,7 +1330,7 @@ private bool ShouldRetry(HttpStatusCode code) { int intCode = (int)code; - if (((intCode == 304) || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0) + if ((intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0) { return true; } From 69c71d4fa45a4bb35e0d20dfe39f7bd461a04470 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:25:34 +0100 Subject: [PATCH 06/18] remove more unnecessary parenthesis --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c03d5b5d402..821edff217b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -678,12 +678,12 @@ internal virtual void PrepareSession() internal string QualifiedOutFile { - get { return (QualifyFilePath(OutFile)); } + get { return QualifyFilePath(OutFile); } } internal bool ShouldSaveToOutFile { - get { return (!string.IsNullOrEmpty(OutFile)); } + get { return !string.IsNullOrEmpty(OutFile); } } internal bool ShouldWriteToPipeline @@ -746,7 +746,7 @@ private static Uri CheckProtocol(Uri uri) uri = new Uri("http://" + uri.OriginalString); } - return (uri); + return uri; } private string QualifyFilePath(string path) @@ -788,7 +788,7 @@ private ErrorRecord GetValidationError(string msg, string errorId) { var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); + return error; } private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) @@ -796,7 +796,7 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object msg = string.Format(CultureInfo.InvariantCulture, msg, args); var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); + return error; } private bool IsStandardMethodSet() @@ -1153,7 +1153,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } } - return (request); + return request; } internal virtual void FillRequestStream(HttpRequestMessage request) @@ -1817,7 +1817,7 @@ internal long SetRequestContent(HttpRequestMessage request, IDictionary content) throw new ArgumentNullException(nameof(content)); string body = FormatDictionary(content); - return (SetRequestContent(request, body)); + return SetRequestContent(request, body); } internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) From 77025188238523a4017d27a94960e6a0c4cf7755 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:31:03 +0100 Subject: [PATCH 07/18] { --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 821edff217b..10dc7256ab4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -739,7 +739,10 @@ private Uri PrepareUri(Uri uri) private static Uri CheckProtocol(Uri uri) { - if (uri == null) { throw new ArgumentNullException(nameof(uri)); } + if (uri == null) + { + throw new ArgumentNullException(nameof(uri)); + } if (!uri.IsAbsoluteUri) { @@ -1455,7 +1458,10 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) + { + throw new ArgumentNullException(nameof(response)); + } } #endregion Virtual Methods From 02b6fdebc9aac20d8b0aab9be8ceaf7ecf23d2f9 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:39:21 +0100 Subject: [PATCH 08/18] body of if wrapped in curly brackets --- .../Common/WebRequestPSCmdlet.Common.cs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 10dc7256ab4..6db45be7d69 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1343,9 +1343,15 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client == null) { throw new ArgumentNullException(nameof(client)); } + if (client == null) + { + throw new ArgumentNullException(nameof(client)); + } - if (request == null) { throw new ArgumentNullException(nameof(request)); } + if (request == null) + { + throw new ArgumentNullException(nameof(request)); + } // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; @@ -1669,9 +1675,14 @@ protected override void ProcessRecord() internal long SetRequestContent(HttpRequestMessage request, byte[] content) { if (request == null) + { throw new ArgumentNullException(nameof(request)); + } + if (content == null) + { return 0; + } var byteArrayContent = new ByteArrayContent(content); request.Content = byteArrayContent; @@ -1692,11 +1703,15 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) internal long SetRequestContent(HttpRequestMessage request, string content) { if (request == null) + { throw new ArgumentNullException(nameof(request)); + } if (content == null) + { return 0; - + } + Encoding encoding = null; if (ContentType != null) { @@ -1818,9 +1833,14 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { if (request == null) + { throw new ArgumentNullException(nameof(request)); + } + if (content == null) + { throw new ArgumentNullException(nameof(content)); + } string body = FormatDictionary(content); return SetRequestContent(request, body); From a2099f4f4312f7c372139bfa5c855640264220fe Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 6 Dec 2022 14:17:50 +0100 Subject: [PATCH 09/18] cleanup MaximumRedirection; clearer definition of default MaximumRetryCount --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index d81a647b3df..adb728b84da 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -237,21 +237,14 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int MaximumRedirection - { - get { return _maximumRedirection; } - - set { _maximumRedirection = value; } - } - - private int _maximumRedirection = -1; + public virtual int MaximumRedirection { get; set; } = -1; /// /// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request. /// [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int MaximumRetryCount { get; set; } + public virtual int MaximumRetryCount { get; set; } = 0; /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. From 1eadb0164b987bddddfabbcda33cd598b195e73d Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 6 Dec 2022 14:21:25 +0100 Subject: [PATCH 10/18] cleanup Method and CustomMethod get-set --- .../Common/WebRequestPSCmdlet.Common.cs | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index adb728b84da..70c86717719 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -262,14 +262,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// [Parameter(ParameterSetName = "StandardMethod")] [Parameter(ParameterSetName = "StandardMethodNoProxy")] - public virtual WebRequestMethod Method - { - get { return _method; } - - set { _method = value; } - } - - private WebRequestMethod _method = WebRequestMethod.Default; + public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default; /// /// Gets or sets the CustomMethod property. @@ -278,14 +271,7 @@ public virtual WebRequestMethod Method [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] [Alias("CM")] [ValidateNotNullOrEmpty] - public virtual string CustomMethod - { - get { return _customMethod; } - - set { _customMethod = value; } - } - - private string _customMethod; + public virtual string CustomMethod { get; set; } #endregion From 846d0ef87f3de9a7300cabf234a08945e7908a8a Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 6 Dec 2022 14:29:52 +0100 Subject: [PATCH 11/18] replace get { return with => --- .../Common/WebRequestPSCmdlet.Common.cs | 25 ++++--------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 70c86717719..e81b23cb214 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -655,33 +655,18 @@ internal virtual void PrepareSession() #region Helper Properties - internal string QualifiedOutFile - { - get { return QualifyFilePath(OutFile); } - } + internal string QualifiedOutFile => QualifyFilePath(OutFile); - internal bool ShouldSaveToOutFile - { - get { return !string.IsNullOrEmpty(OutFile); } - } + internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile); - internal bool ShouldWriteToPipeline - { - get { return (!ShouldSaveToOutFile || PassThru); } - } + internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru; - internal bool ShouldCheckHttpStatus - { - get { return !SkipHttpErrorCheck; } - } + internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; /// /// Determines whether writing to a file should Resume and append rather than overwrite. /// - internal bool ShouldResume - { - get { return (Resume.IsPresent && _resumeSuccess); } - } + internal bool ShouldResume => Resume.IsPresent && _resumeSuccess; #endregion Helper Properties From 778b5cdd166c325c68512406a681ec5a8a430916 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 13 Dec 2022 22:35:24 +0100 Subject: [PATCH 12/18] revert =0 --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index e81b23cb214..c02912dbe72 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -244,7 +244,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int MaximumRetryCount { get; set; } = 0; + public virtual int MaximumRetryCount { get; set; }; /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. From e803d640f3741415c82b352d1452cadb28ceb052 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 13 Dec 2022 22:44:33 +0100 Subject: [PATCH 13/18] != -> is not - remove leftover ; == -> is remove useless return; fixed errors revert --- .../Common/WebRequestPSCmdlet.Common.cs | 190 +++++++++--------- 1 file changed, 95 insertions(+), 95 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c02912dbe72..e219e9872ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -244,7 +244,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int MaximumRetryCount { get; set; }; + public virtual int MaximumRetryCount { get; set; } /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. @@ -389,89 +389,89 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet internal virtual void ValidateParameters() { // sessions - if (WebSession != null && SessionVariable != null) + if (WebSession is not null && SessionVariable is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } // Authentication - if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) + if (UseDefaultCredentials && Authentication is not WebAuthenticationType.None) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } - if (Authentication != WebAuthenticationType.None && Token != null && Credential != null) + if (Authentication is not WebAuthenticationType.None && Token is not null && Credential is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } - if (Authentication == WebAuthenticationType.Basic && Credential == null) + if (Authentication is WebAuthenticationType.Basic && Credential is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token == null) + if ((Authentication is WebAuthenticationType.OAuth || Authentication is WebAuthenticationType.Bearer) && Token is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https") + if (!AllowUnencryptedAuthentication && Authentication is not WebAuthenticationType.None && Uri.Scheme is not "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && Uri.Scheme != "https") + if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme is not "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } // credentials - if (UseDefaultCredentials && Credential != null) + if (UseDefaultCredentials && Credential is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server - if (ProxyUseDefaultCredentials && ProxyCredential != null) + if (ProxyUseDefaultCredentials && ProxyCredential is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if (Proxy == null && (ProxyCredential != null || ProxyUseDefaultCredentials)) + else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } // request body content - if (Body != null && InFile != null) + if (Body is not null && InFile is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } - if (Body != null && Form != null) + if (Body is not null && Form is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } - if (InFile != null && Form != null) + if (InFile is not null && Form is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); ThrowTerminatingError(error); } // validate InFile path - if (InFile != null) + if (InFile is not null) { ProviderInfo provider = null; ErrorRecord errorRecord = null; @@ -490,7 +490,7 @@ internal virtual void ValidateParameters() { errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } - else if (providerPaths.Count == 0) + else if (providerPaths.Count is 0) { errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } @@ -519,21 +519,21 @@ internal virtual void ValidateParameters() errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } - if (errorRecord != null) + if (errorRecord is not null) { ThrowTerminatingError(errorRecord); } } // output ?? - if (PassThru && OutFile == null) + if (PassThru && OutFile is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); } // Resume requires OutFile. - if (Resume.IsPresent && OutFile == null) + if (Resume.IsPresent && OutFile is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); ThrowTerminatingError(error); @@ -545,7 +545,7 @@ internal virtual void PrepareSession() // make sure we have a valid WebRequestSession object to work with WebSession ??= new WebRequestSession(); - if (SessionVariable != null) + if (SessionVariable is not null) { // save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; @@ -553,7 +553,7 @@ internal virtual void PrepareSession() } // handle credentials - if (Credential != null && Authentication == WebAuthenticationType.None) + if (Credential is not null && Authentication is WebAuthenticationType.None) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); @@ -562,7 +562,7 @@ internal virtual void PrepareSession() // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } - else if ((Credential != null || Token != null) && Authentication != WebAuthenticationType.None) + else if ((Credential is not null || Token is not null) && Authentication is not WebAuthenticationType.None) { ProcessAuthentication(); } @@ -571,13 +571,13 @@ internal virtual void PrepareSession() WebSession.UseDefaultCredentials = true; } - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { X509Store store = new(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); - if (tbCollection.Count == 0) + if (tbCollection.Count is 0) { CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); throw ex; @@ -590,23 +590,23 @@ internal virtual void PrepareSession() } } - if (Certificate != null) + if (Certificate is not null) { WebSession.AddCertificate(Certificate); } // handle the user agent - if (UserAgent != null) + if (UserAgent is not null) { // store the UserAgent string WebSession.UserAgent = UserAgent; } - if (Proxy != null) + if (Proxy is not null) { WebProxy webProxy = new(Proxy); webProxy.BypassProxyOnLocal = false; - if (ProxyCredential != null) + if (ProxyCredential is not null) { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } @@ -626,7 +626,7 @@ internal virtual void PrepareSession() } // store the other supplied headers - if (Headers != null) + if (Headers is not null) { foreach (string key in Headers.Keys) { @@ -679,12 +679,12 @@ private Uri PrepareUri(Uri uri) // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if (bodyAsDictionary != null - && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) - || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) + if (bodyAsDictionary is not null + && ((IsStandardMethodSet() && (Method is WebRequestMethod.Default || Method is WebRequestMethod.Get)) + || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "GET"))) { UriBuilder uriBuilder = new(uri); - if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) + if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) { uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); } @@ -703,7 +703,7 @@ private Uri PrepareUri(Uri uri) private static Uri CheckProtocol(Uri uri) { - if (uri == null) + if (uri is null) { throw new ArgumentNullException(nameof(uri)); } @@ -724,7 +724,7 @@ private string QualifyFilePath(string path) private static string FormatDictionary(IDictionary content) { - if (content == null) + if (content is null) throw new ArgumentNullException(nameof(content)); StringBuilder bodyBuilder = new(); @@ -740,7 +740,7 @@ private static string FormatDictionary(IDictionary content) // URLEncode the key and value string encodedKey = WebUtility.UrlEncode(key); string encodedValue = string.Empty; - if (value != null) + if (value is not null) { encodedValue = WebUtility.UrlEncode(value.ToString()); } @@ -768,12 +768,12 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object private bool IsStandardMethodSet() { - return (ParameterSetName == "StandardMethod" || ParameterSetName == "StandardMethodNoProxy"); + return (ParameterSetName is "StandardMethod" || ParameterSetName is "StandardMethodNoProxy"); } private bool IsCustomMethodSet() { - return (ParameterSetName == "CustomMethod" || ParameterSetName == "CustomMethodNoProxy"); + return (ParameterSetName is "CustomMethod" || ParameterSetName is "CustomMethodNoProxy"); } private string GetBasicAuthorizationHeader() @@ -791,11 +791,11 @@ private string GetBearerAuthorizationHeader() private void ProcessAuthentication() { - if (Authentication == WebAuthenticationType.Basic) + if (Authentication is WebAuthenticationType.Basic) { WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader(); } - else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth) + else if (Authentication is WebAuthenticationType.Bearer || Authentication is WebAuthenticationType.OAuth) { WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader(); } @@ -946,7 +946,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) // the UseDefaultCredentials flag overrides other supplied credentials handler.UseDefaultCredentials = true; } - else if (WebSession.Credentials != null) + else if (WebSession.Credentials is not null) { handler.Credentials = WebSession.Credentials; } @@ -955,12 +955,12 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) { handler.UseProxy = false; } - else if (WebSession.Proxy != null) + else if (WebSession.Proxy is not null) { handler.Proxy = WebSession.Proxy; } - if (WebSession.Certificates != null) + if (WebSession.Certificates is not null) { handler.ClientCertificates.AddRange(WebSession.Certificates); } @@ -978,7 +978,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) } else if (WebSession.MaximumRedirection > -1) { - if (WebSession.MaximumRedirection == 0) + if (WebSession.MaximumRedirection is 0) { handler.AllowAutoRedirect = false; } @@ -993,7 +993,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) HttpClient httpClient = new(handler); // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) - if (TimeoutSec == 0) + if (TimeoutSec is 0) { // A zero timeout means infinite httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); @@ -1094,7 +1094,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'Transfer-Encoding' - if (TransferEncoding != null) + if (TransferEncoding is not null) { request.Headers.TransferEncodingChunked = true; var headerValue = new TransferCodingHeaderValue(TransferEncoding); @@ -1125,16 +1125,16 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request == null) { throw new ArgumentNullException(nameof(request)); } + if (request is null) { throw new ArgumentNullException(nameof(request)); } // set the content type - if (ContentType != null) + if (ContentType is not null) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; // request } - // ContentType == null - else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) + // ContentType is null + else if (Method is WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "POST")) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST string contentType = null; @@ -1145,7 +1145,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } } - if (Form != null) + if (Form is not null) { // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first WebSession.ContentHeaders.Clear(); @@ -1160,13 +1160,13 @@ internal virtual void FillRequestStream(HttpRequestMessage request) SetRequestContent(request, formData); } // coerce body into a usable form - else if (Body != null) + else if (Body is not null) { object content = Body; // make sure we're using the base object of the body, not the PSObject wrapper PSObject psBody = Body as PSObject; - if (psBody != null) + if (psBody is not null) { content = psBody.BaseObject; } @@ -1203,7 +1203,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); } } - else if (InFile != null) // copy InFile data + else if (InFile is not null) // copy InFile data { try { @@ -1225,7 +1225,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (request.Content is null) { // If this is a Get request and there is no content, then don't fill in the content as empty content gets rejected by some web services per RFC7230 - if ((IsStandardMethodSet() && request.Method == HttpMethod.Get && ContentType is null) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")) + if ((IsStandardMethodSet() && request.Method == HttpMethod.Get && ContentType is null) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "GET")) { return; } @@ -1266,8 +1266,8 @@ private static bool IsRedirectCode(HttpStatusCode code) return ( (intCode >= 300 && intCode < 304) || - intCode == 307 || - intCode == 308 + intCode is 307 || + intCode is 308 ); } @@ -1277,13 +1277,13 @@ private static bool IsRedirectToGet(HttpStatusCode code) { return ( - code == HttpStatusCode.Found || - code == HttpStatusCode.Moved || - code == HttpStatusCode.Redirect || - code == HttpStatusCode.RedirectMethod || - code == HttpStatusCode.SeeOther || - code == HttpStatusCode.Ambiguous || - code == HttpStatusCode.MultipleChoices + code is HttpStatusCode.Found || + code is HttpStatusCode.Moved || + code is HttpStatusCode.Redirect || + code is HttpStatusCode.RedirectMethod || + code is HttpStatusCode.SeeOther || + code is HttpStatusCode.Ambiguous || + code is HttpStatusCode.MultipleChoices ); } @@ -1294,18 +1294,18 @@ private bool ShouldRetry(HttpStatusCode code) return ( - (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 + (intCode is 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 ); } internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client == null) + if (client is null) { throw new ArgumentNullException(nameof(client)); } - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } @@ -1323,7 +1323,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); - if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) + if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location is not null) { _cancelToken.Cancel(); _cancelToken = null; @@ -1336,7 +1336,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // For selected redirects that used POST, GET must be used with the // redirected Location. // Since GET is the default; POST only occurs when -Method POST is used. - if (Method == WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) + if (Method is WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) { // See https://msdn.microsoft.com/library/system.net.httpstatuscode(v=vs.110).aspx Method = WebRequestMethod.Get; @@ -1355,7 +1355,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // This happens when the local file is larger than the remote file. // If the size of the remote file is the same as the local file, there is nothing to resume. if (Resume.IsPresent && - response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && + response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && (response.Content.Headers.ContentRange.HasLength && response.Content.Headers.ContentRange.Length != _resumeFileSize)) { @@ -1371,7 +1371,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM { FillRequestStream(requestWithoutRange); long requestContentLength = 0; - if (requestWithoutRange.Content != null) + if (requestWithoutRange.Content is not null) { requestContentLength = requestWithoutRange.Content.Headers.ContentLength.Value; } @@ -1389,9 +1389,9 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM } } - _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent; + _resumeSuccess = response.StatusCode is HttpStatusCode.PartialContent; - // When MaximumRetryCount is not specified, the totalRequests == 1. + // When MaximumRetryCount is not specified, the totalRequests is 1. if (totalRequests > 1 && ShouldRetry(response.StatusCode)) { string retryMessage = string.Format( @@ -1421,7 +1421,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) + if (response is null) { throw new ArgumentNullException(nameof(response)); } @@ -1444,8 +1444,8 @@ protected override void ProcessRecord() // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession != null && - WebSession.Headers != null && + bool keepAuthorization = WebSession is not null && + WebSession.Headers is not null && PreserveAuthorizationOnRedirect.IsPresent && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); @@ -1471,7 +1471,7 @@ protected override void ProcessRecord() try { long requestContentLength = 0; - if (request.Content != null) + if (request.Content is not null) requestContentLength = request.Content.Headers.ContentLength.Value; string reqVerboseMsg = string.Format( @@ -1499,7 +1499,7 @@ protected override void ProcessRecord() // Check if the Resume range was not satisfiable because the file already completed downloading. // This happens when the local file is the same size as the remote file. if (Resume.IsPresent && - response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && + response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && response.Content.Headers.ContentRange.HasLength && response.Content.Headers.ContentRange.Length == _resumeFileSize) { @@ -1560,7 +1560,7 @@ protected override void ProcessRecord() // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are // impossible to detect programmatically when we hit this limit. By handling this ourselves // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect == false" + if (WebSession.MaximumRedirection is 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect is false" { ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); @@ -1570,7 +1570,7 @@ protected override void ProcessRecord() catch (HttpRequestException ex) { ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException != null) + if (ex.InnerException is not null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } @@ -1626,12 +1626,12 @@ protected override void ProcessRecord() /// internal long SetRequestContent(HttpRequestMessage request, byte[] content) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } - if (content == null) + if (content is null) { return 0; } @@ -1654,18 +1654,18 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// internal long SetRequestContent(HttpRequestMessage request, string content) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } - if (content == null) + if (content is null) { return 0; } Encoding encoding = null; - if (ContentType != null) + if (ContentType is not null) { // If Content-Type contains the encoding format (as CharSet), use this encoding format // to encode the Body of the WebRequest sent to the server. Default Encoding format @@ -1707,10 +1707,10 @@ internal long SetRequestContent(HttpRequestMessage request, string content) internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { - if (request == null) + if (request is null) throw new ArgumentNullException(nameof(request)); - if (xmlNode == null) + if (xmlNode is null) return 0; byte[] bytes = null; @@ -1744,9 +1744,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) { - if (request == null) + if (request is null) throw new ArgumentNullException(nameof(request)); - if (contentStream == null) + if (contentStream is null) throw new ArgumentNullException(nameof(contentStream)); var streamContent = new StreamContent(contentStream); @@ -1767,12 +1767,12 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } - if (multipartContent == null) + if (multipartContent is null) { throw new ArgumentNullException(nameof(multipartContent)); } @@ -1784,12 +1784,12 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { - if (request == null) + if (request is null) { throw new ArgumentNullException(nameof(request)); } - if (content == null) + if (content is null) { throw new ArgumentNullException(nameof(content)); } @@ -1800,7 +1800,7 @@ internal long SetRequestContent(HttpRequestMessage request, IDictionary content) internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) { - if (_relationLink == null) + if (_relationLink is null) { // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288) _relationLink = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1845,7 +1845,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { - if (formData == null) + if (formData is null) { throw new ArgumentNullException(nameof(formData)); } From 794edcbf44d8a8037979d63e0d66023620642cd4 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 15 Dec 2022 01:53:21 +0100 Subject: [PATCH 14/18] fix double blank line --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index ac10150633b..4e81cd7b854 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -723,7 +723,6 @@ private static string FormatDictionary(IDictionary content) { ArgumentNullException.ThrowIfNull(content); - StringBuilder bodyBuilder = new(); foreach (string key in content.Keys) { @@ -1301,7 +1300,6 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM ArgumentNullException.ThrowIfNull(request); - // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; HttpRequestMessage req = request; From 6011edcdbf409c56e25b3f3e0080ec7d3a3fc679 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:32:09 +0100 Subject: [PATCH 15/18] reverted --- .../Common/WebRequestPSCmdlet.Common.cs | 92 +++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 4e81cd7b854..95cfc0b0450 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -396,37 +396,37 @@ internal virtual void ValidateParameters() } // Authentication - if (UseDefaultCredentials && Authentication is not WebAuthenticationType.None) + if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } - if (Authentication is not WebAuthenticationType.None && Token is not null && Credential is not null) + if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } - if (Authentication is WebAuthenticationType.Basic && Credential is null) + if (Authentication == WebAuthenticationType.Basic && Credential is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if ((Authentication is WebAuthenticationType.OAuth || Authentication is WebAuthenticationType.Bearer) && Token is null) + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && Authentication is not WebAuthenticationType.None && Uri.Scheme is not "https") + if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme is not "https") + if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); @@ -490,7 +490,7 @@ internal virtual void ValidateParameters() { errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } - else if (providerPaths.Count is 0) + else if (providerPaths.Count == 0) { errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } @@ -562,7 +562,7 @@ internal virtual void PrepareSession() // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } - else if ((Credential is not null || Token is not null) && Authentication is not WebAuthenticationType.None) + else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None) { ProcessAuthentication(); } @@ -577,7 +577,7 @@ internal virtual void PrepareSession() store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); - if (tbCollection.Count is 0) + if (tbCollection.Count == 0) { CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); throw ex; @@ -680,8 +680,8 @@ private Uri PrepareUri(Uri uri) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); if (bodyAsDictionary is not null - && ((IsStandardMethodSet() && (Method is WebRequestMethod.Default || Method is WebRequestMethod.Get)) - || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "GET"))) + && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) + || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { UriBuilder uriBuilder = new(uri); if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) @@ -764,12 +764,12 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object private bool IsStandardMethodSet() { - return (ParameterSetName is "StandardMethod" || ParameterSetName is "StandardMethodNoProxy"); + return (ParameterSetName == "StandardMethod" || ParameterSetName == "StandardMethodNoProxy"); } private bool IsCustomMethodSet() { - return (ParameterSetName is "CustomMethod" || ParameterSetName is "CustomMethodNoProxy"); + return (ParameterSetName == "CustomMethod" || ParameterSetName == "CustomMethodNoProxy"); } private string GetBasicAuthorizationHeader() @@ -787,11 +787,11 @@ private string GetBearerAuthorizationHeader() private void ProcessAuthentication() { - if (Authentication is WebAuthenticationType.Basic) + if (Authentication == WebAuthenticationType.Basic) { WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader(); } - else if (Authentication is WebAuthenticationType.Bearer || Authentication is WebAuthenticationType.OAuth) + else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth) { WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader(); } @@ -974,7 +974,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) } else if (WebSession.MaximumRedirection > -1) { - if (WebSession.MaximumRedirection is 0) + if (WebSession.MaximumRedirection == 0) { handler.AllowAutoRedirect = false; } @@ -989,7 +989,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) HttpClient httpClient = new(handler); // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) - if (TimeoutSec is 0) + if (TimeoutSec == 0) { // A zero timeout means infinite httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); @@ -1130,7 +1130,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) // request } // ContentType is null - else if (Method is WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "POST")) + else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST string contentType = null; @@ -1167,27 +1167,27 @@ internal virtual void FillRequestStream(HttpRequestMessage request) content = psBody.BaseObject; } - if (content is FormObject form) + if (content == FormObject form) { SetRequestContent(request, form.Fields); } - else if (content is IDictionary dictionary && request.Method != HttpMethod.Get) + else if (content == IDictionary dictionary && request.Method != HttpMethod.Get) { SetRequestContent(request, dictionary); } - else if (content is XmlNode xmlNode) + else if (content == XmlNode xmlNode) { SetRequestContent(request, xmlNode); } - else if (content is Stream stream) + else if (content == Stream stream) { SetRequestContent(request, stream); } - else if (content is byte[] bytes) + else if (content == byte[] bytes) { SetRequestContent(request, bytes); } - else if (content is MultipartFormDataContent multipartFormDataContent) + else if (content == MultipartFormDataContent multipartFormDataContent) { WebSession.ContentHeaders.Clear(); SetRequestContent(request, multipartFormDataContent); @@ -1221,7 +1221,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (request.Content is null) { // If this is a Get request and there is no content, then don't fill in the content as empty content gets rejected by some web services per RFC7230 - if ((IsStandardMethodSet() && request.Method == HttpMethod.Get && ContentType is null) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() is "GET")) + if ((IsStandardMethodSet() && request.Method == HttpMethod.Get && ContentType is null) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")) { return; } @@ -1262,8 +1262,8 @@ private static bool IsRedirectCode(HttpStatusCode code) return ( (intCode >= 300 && intCode < 304) || - intCode is 307 || - intCode is 308 + intCode == 307 || + intCode == 308 ); } @@ -1273,13 +1273,13 @@ private static bool IsRedirectToGet(HttpStatusCode code) { return ( - code is HttpStatusCode.Found || - code is HttpStatusCode.Moved || - code is HttpStatusCode.Redirect || - code is HttpStatusCode.RedirectMethod || - code is HttpStatusCode.SeeOther || - code is HttpStatusCode.Ambiguous || - code is HttpStatusCode.MultipleChoices + code == HttpStatusCode.Found || + code == HttpStatusCode.Moved || + code == HttpStatusCode.Redirect || + code == HttpStatusCode.RedirectMethod || + code == HttpStatusCode.SeeOther || + code == HttpStatusCode.Ambiguous || + code == HttpStatusCode.MultipleChoices ); } @@ -1290,7 +1290,7 @@ private bool ShouldRetry(HttpStatusCode code) return ( - (intCode is 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 + (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 ); } @@ -1326,7 +1326,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // For selected redirects that used POST, GET must be used with the // redirected Location. // Since GET is the default; POST only occurs when -Method POST is used. - if (Method is WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) + if (Method == WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) { // See https://msdn.microsoft.com/library/system.net.httpstatuscode(v=vs.110).aspx Method = WebRequestMethod.Get; @@ -1345,7 +1345,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // This happens when the local file is larger than the remote file. // If the size of the remote file is the same as the local file, there is nothing to resume. if (Resume.IsPresent && - response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && + response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && (response.Content.Headers.ContentRange.HasLength && response.Content.Headers.ContentRange.Length != _resumeFileSize)) { @@ -1388,7 +1388,7 @@ response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && // If the status code is 429 get the retry interval from the Headers. // Ignore broken header and its value. - if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + if (response.StatusCode == HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) { try { @@ -1506,7 +1506,7 @@ WebSession.Headers is not null && // Check if the Resume range was not satisfiable because the file already completed downloading. // This happens when the local file is the same size as the remote file. if (Resume.IsPresent && - response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && + response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && response.Content.Headers.ContentRange.HasLength && response.Content.Headers.ContentRange.Length == _resumeFileSize) { @@ -1567,7 +1567,7 @@ response.StatusCode is HttpStatusCode.RequestedRangeNotSatisfiable && // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are // impossible to detect programmatically when we hit this limit. By handling this ourselves // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection is 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect is false" + if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect is false" { ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); @@ -1715,7 +1715,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc?.FirstChild is XmlDeclaration) + if (doc?.FirstChild == XmlDeclaration) { XmlDeclaration decl = doc.FirstChild as XmlDeclaration; Encoding encoding = Encoding.GetEncoding(decl.Encoding); @@ -1838,19 +1838,19 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers. // Unwrap fieldName PSObjects - if (fieldName is PSObject namePSObject) + if (fieldName == PSObject namePSObject) { fieldName = namePSObject.BaseObject; } // Unwrap fieldValue PSObjects - if (fieldValue is PSObject valuePSObject) + if (fieldValue == PSObject valuePSObject) { fieldValue = valuePSObject.BaseObject; } // Treat a single FileInfo as a FileContent - if (fieldValue is FileInfo file) + if (fieldValue == FileInfo file) { formData.Add(GetMultipartFileContent(fieldName: fieldName, file: file)); return; @@ -1859,14 +1859,14 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Treat Strings and other single values as a StringContent. // If enumeration is false, also treat IEnumerables as StringContents. // String implements IEnumerable so the explicit check is required. - if (!enumerate || fieldValue is string || fieldValue is not IEnumerable) + if (!enumerate || fieldValue == string || fieldValue != IEnumerable) { formData.Add(GetMultipartStringContent(fieldName: fieldName, fieldValue: fieldValue)); return; } // Treat the value as a collection and enumerate it if enumeration is true - if (enumerate && fieldValue is IEnumerable items) + if (enumerate && fieldValue == IEnumerable items) { foreach (var item in items) { From 918e51504b62f94f3b01b3b0d57c5083ad892855 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 15 Dec 2022 12:03:03 +0100 Subject: [PATCH 16/18] fixed --- .../Common/WebRequestPSCmdlet.Common.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 95cfc0b0450..9265013837b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1167,27 +1167,27 @@ internal virtual void FillRequestStream(HttpRequestMessage request) content = psBody.BaseObject; } - if (content == FormObject form) + if (content is FormObject form) { SetRequestContent(request, form.Fields); } - else if (content == IDictionary dictionary && request.Method != HttpMethod.Get) + else if (content is IDictionary dictionary && request.Method != HttpMethod.Get) { SetRequestContent(request, dictionary); } - else if (content == XmlNode xmlNode) + else if (content is XmlNode xmlNode) { SetRequestContent(request, xmlNode); } - else if (content == Stream stream) + else if (content is Stream stream) { SetRequestContent(request, stream); } - else if (content == byte[] bytes) + else if (content is byte[] bytes) { SetRequestContent(request, bytes); } - else if (content == MultipartFormDataContent multipartFormDataContent) + else if (content is MultipartFormDataContent multipartFormDataContent) { WebSession.ContentHeaders.Clear(); SetRequestContent(request, multipartFormDataContent); @@ -1379,7 +1379,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM } } - _resumeSuccess = response.StatusCode is HttpStatusCode.PartialContent; + _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent; // When MaximumRetryCount is not specified, the totalRequests is 1. if (totalRequests > 1 && ShouldRetry(response.StatusCode)) @@ -1388,7 +1388,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // If the status code is 429 get the retry interval from the Headers. // Ignore broken header and its value. - if (response.StatusCode == HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) { try { @@ -1715,7 +1715,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc?.FirstChild == XmlDeclaration) + if (doc?.FirstChild is XmlDeclaration) { XmlDeclaration decl = doc.FirstChild as XmlDeclaration; Encoding encoding = Encoding.GetEncoding(decl.Encoding); @@ -1838,19 +1838,19 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers. // Unwrap fieldName PSObjects - if (fieldName == PSObject namePSObject) + if (fieldName is PSObject namePSObject) { fieldName = namePSObject.BaseObject; } // Unwrap fieldValue PSObjects - if (fieldValue == PSObject valuePSObject) + if (fieldValue is PSObject valuePSObject) { fieldValue = valuePSObject.BaseObject; } // Treat a single FileInfo as a FileContent - if (fieldValue == FileInfo file) + if (fieldValue is FileInfo file) { formData.Add(GetMultipartFileContent(fieldName: fieldName, file: file)); return; @@ -1859,14 +1859,14 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Treat Strings and other single values as a StringContent. // If enumeration is false, also treat IEnumerables as StringContents. // String implements IEnumerable so the explicit check is required. - if (!enumerate || fieldValue == string || fieldValue != IEnumerable) + if (!enumerate || fieldValue is string || fieldValue is not IEnumerable) { formData.Add(GetMultipartStringContent(fieldName: fieldName, fieldValue: fieldValue)); return; } // Treat the value as a collection and enumerate it if enumeration is true - if (enumerate && fieldValue == IEnumerable items) + if (enumerate && fieldValue is IEnumerable items) { foreach (var item in items) { From 657bc3e10c5ebef4689c2929f0a749114731b888 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 15 Dec 2022 21:33:49 +0500 Subject: [PATCH 17/18] Update src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 9265013837b..194a04e0404 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -553,7 +553,7 @@ internal virtual void PrepareSession() } // handle credentials - if (Credential is not null && Authentication is WebAuthenticationType.None) + if (Credential is not null && Authentication == WebAuthenticationType.None) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); From 9aa66155a82ce0fd77978a67a69a91a2e5e99958 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 15 Dec 2022 21:33:56 +0500 Subject: [PATCH 18/18] Update src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 194a04e0404..dbbe169ae3d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1711,7 +1711,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) ArgumentNullException.ThrowIfNull(request); if (xmlNode is null) + { return 0; + } byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument;