Cleanup StreamHelper.cs, WebRequestPSCmdlet.Common.cs and InvokeRestMethodCommand.Common.cs (#18950)

This commit is contained in:
CarloToso
2023-01-17 15:59:52 +05:00
committed by GitHub
parent 2df06f2e20
commit 3fb4bb277b
3 changed files with 34 additions and 123 deletions
@@ -25,32 +25,6 @@ namespace Microsoft.PowerShell.Commands
{
#region Parameters
/// <summary>
/// Gets or sets the parameter Method.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "StandardMethodNoProxy")]
public override WebRequestMethod Method
{
get => base.Method;
set => base.Method = value;
}
/// <summary>
/// Gets or sets the parameter CustomMethod.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "CustomMethod")]
[Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
[Alias("CM")]
[ValidateNotNullOrEmpty]
public override string CustomMethod
{
get => base.CustomMethod;
set => base.CustomMethod = value.ToUpperInvariant();
}
/// <summary>
/// Enable automatic following of rel links.
/// </summary>
@@ -60,7 +60,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// No SSL protocol will be set and the system defaults will be used.
/// </summary>
Default = 0,
Default = SslProtocols.None,
/// <summary>
/// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2.
@@ -433,13 +433,7 @@ namespace Microsoft.PowerShell.Commands
ThrowTerminatingError(error);
}
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 != "https")
if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https")
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
@@ -486,12 +480,11 @@ namespace Microsoft.PowerShell.Commands
// Validate InFile path
if (InFile is not null)
{
ProviderInfo provider = null;
ErrorRecord errorRecord = null;
try
{
Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider);
Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider);
if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
{
@@ -688,10 +681,9 @@ namespace Microsoft.PowerShell.Commands
{
uri = CheckProtocol(uri);
// before creating the web request,
// Before creating the web request,
// preprocess Body if content is a dictionary and method is GET (set as query)
IDictionary bodyAsDictionary;
LanguagePrimitives.TryConvertTo<IDictionary>(Body, out bodyAsDictionary);
LanguagePrimitives.TryConvertTo<IDictionary>(Body, out IDictionary bodyAsDictionary);
if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET"))
{
UriBuilder uriBuilder = new(uri);
@@ -970,16 +962,8 @@ namespace Microsoft.PowerShell.Commands
HttpClient httpClient = new(handler);
// check timeout setting (in seconds instead of milliseconds as in HttpWebRequest)
if (TimeoutSec == 0)
{
// A zero timeout means infinite
httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
}
else if (TimeoutSec > 0)
{
httpClient.Timeout = new TimeSpan(0, 0, TimeoutSec);
}
// Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest)
httpClient.Timeout = TimeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : new TimeSpan(0, 0, TimeoutSec);
return httpClient;
}
@@ -1028,8 +1012,7 @@ namespace Microsoft.PowerShell.Commands
}
// Set 'User-Agent' if WebSession.Headers doesn't already contain it
string userAgent = null;
if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out userAgent))
if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent))
{
WebSession.UserAgent = userAgent;
}
@@ -1095,8 +1078,7 @@ namespace Microsoft.PowerShell.Commands
else if (request.Method == HttpMethod.Post)
{
// Win8:545310 Invoke-WebRequest does not properly set MIME type for POST
string contentType = null;
WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out contentType);
WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType);
if (string.IsNullOrEmpty(contentType))
{
WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded";
@@ -1280,7 +1262,7 @@ namespace Microsoft.PowerShell.Commands
_cancelToken.Cancel();
_cancelToken = null;
// if explicit count was provided, reduce it for this redirection.
// If explicit count was provided, reduce it for this redirection.
if (WebSession.MaximumRedirection > 0)
{
WebSession.MaximumRedirection--;
@@ -1441,7 +1423,9 @@ namespace Microsoft.PowerShell.Commands
{
long requestContentLength = 0;
if (request.Content is not null)
{
requestContentLength = request.Content.Headers.ContentLength.Value;
}
string reqVerboseMsg = string.Format(
CultureInfo.CurrentCulture,
@@ -1641,16 +1625,7 @@ namespace Microsoft.PowerShell.Commands
encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet);
}
}
catch (FormatException ex)
{
if (!SkipHeaderValidation)
{
var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex);
ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType);
ThrowTerminatingError(er);
}
}
catch (ArgumentException ex)
catch (Exception ex) when (ex is FormatException || ex is ArgumentException)
{
if (!SkipHeaderValidation)
{
@@ -1687,7 +1662,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml);
bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null);
}
var byteArrayContent = new ByteArrayContent(bytes);
@@ -1764,8 +1739,7 @@ namespace Microsoft.PowerShell.Commands
// We only support the URL in angle brackets and `rel`, other attributes are ignored
// user can still parse it themselves via the Headers property
const string pattern = "<(?<url>.*?)>;\\s*rel=(?<quoted>\")?(?<rel>(?(quoted).*?|[^,;]*))(?(quoted)\")";
IEnumerable<string> links;
if (response.Headers.TryGetValues("Link", out links))
if (response.Headers.TryGetValues("Link", out IEnumerable<string> links))
{
foreach (string linkHeader in links)
{
@@ -38,8 +38,7 @@ namespace Microsoft.PowerShell.Commands
/// <param name="initialCapacity"></param>
/// <param name="cmdlet">Owner cmdlet if any.</param>
/// <param name="contentLength">Expected download size in Bytes.</param>
internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength)
: base(initialCapacity)
internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) : base(initialCapacity)
{
this._contentLength = contentLength;
_originalStreamToProxy = stream;
@@ -49,43 +48,15 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// </summary>
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanRead => true;
/// <summary>
/// </summary>
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanSeek => true;
/// <summary>
/// </summary>
public override bool CanTimeout
{
get
{
return base.CanTimeout;
}
}
/// <summary>
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
public override bool CanWrite => true;
/// <summary>
/// </summary>
@@ -215,7 +186,10 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
private void Initialize()
{
if (_isInitialized) { return; }
if (_isInitialized)
{
return;
}
_isInitialized = true;
try
@@ -226,7 +200,7 @@ namespace Microsoft.PowerShell.Commands
string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength);
for (int read = 1; read > 0; totalRead += read)
{
if (_ownerCmdlet != null)
if (_ownerCmdlet is not null)
{
record.StatusDescription = StringUtil.Format(
WebCmdletStrings.ReadResponseProgressStatus,
@@ -254,14 +228,14 @@ namespace Microsoft.PowerShell.Commands
}
}
if (_ownerCmdlet != null)
if (_ownerCmdlet is not null)
{
record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead);
record.RecordType = ProgressRecordType.Completed;
_ownerCmdlet.WriteProgress(record);
}
// make sure the length is set appropriately
// Make sure the length is set appropriately
base.SetLength(totalRead);
base.Seek(0, SeekOrigin.Begin);
}
@@ -281,7 +255,7 @@ namespace Microsoft.PowerShell.Commands
internal const int ChunkSize = 10000;
// just picked a random number
// Just picked a random number
internal const int ActivityId = 174593042;
#endregion Constants
@@ -377,8 +351,6 @@ namespace Microsoft.PowerShell.Commands
bool completed = false;
int byteIndex = 0;
int bytesUsed;
int charsUsed;
while (!completed)
{
@@ -386,7 +358,7 @@ namespace Microsoft.PowerShell.Commands
bool flush = (bytesRead == 0);
decoder.Convert(bytes, byteIndex, bytesRead - byteIndex,
chars, 0, useBufferSize, flush,
out bytesUsed, out charsUsed, out completed);
out int bytesUsed, out int charsUsed, out completed);
// The conversion produced the number of characters indicated by charsUsed. Write that number
// of characters to our result buffer
@@ -447,7 +419,7 @@ namespace Microsoft.PowerShell.Commands
internal static string DecodeStream(Stream stream, ref Encoding encoding)
{
bool isDefaultEncoding = false;
if (encoding == null)
if (encoding is null)
{
// Use the default encoding if one wasn't provided
encoding = ContentHelper.GetDefaultEncoding();
@@ -459,7 +431,7 @@ namespace Microsoft.PowerShell.Commands
{
do
{
// check for a charset attribute on the meta element to override the default
// Check for a charset attribute on the meta element to override the default
// we only look within the first 1k characters as the meta tag is in the head
// tag which is at the start of the document
Match match = s_metaexp.Match(content.Substring(0, Math.Min(content.Length, 1024)));
@@ -472,7 +444,8 @@ namespace Microsoft.PowerShell.Commands
{
stream.Seek(0, SeekOrigin.Begin);
content = StreamToString(stream, localEncoding);
// report the encoding used.
// Report the encoding used.
encoding = localEncoding;
}
}
@@ -484,23 +457,13 @@ namespace Microsoft.PowerShell.Commands
internal static byte[] EncodeToBytes(string str, Encoding encoding)
{
// just use the default encoding if one wasn't provided
// Just use the default encoding if one wasn't provided
encoding ??= ContentHelper.GetDefaultEncoding();
return encoding.GetBytes(str);
}
internal static byte[] EncodeToBytes(string str)
{
return EncodeToBytes(str, null);
}
internal static Stream GetResponseStream(HttpResponseMessage response)
{
Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
return responseStream;
}
internal static Stream GetResponseStream(HttpResponseMessage response) => response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
#endregion Static Methods
}