From c77aa9e34ff7b611947ff7ee36f8cb05907895d0 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 25 Nov 2020 08:53:10 +0000 Subject: [PATCH] Fix IDE0090: Simplify new expression part 4.2 `src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/` Contributes to #14202. https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../BasicHtmlWebResponseObject.Common.cs | 8 ++--- .../WebCmdlet/Common/ContentHelper.Common.cs | 2 +- .../Common/InvokeRestMethodCommand.Common.cs | 4 +-- .../Common/WebRequestPSCmdlet.Common.cs | 34 +++++++++---------- .../WebCmdlet/ConvertFromJsonCommand.cs | 2 +- .../utility/WebCmdlet/ConvertToJsonCommand.cs | 4 +-- .../commands/utility/WebCmdlet/JsonObject.cs | 8 ++--- .../commands/utility/WebCmdlet/PSUserAgent.cs | 4 +-- .../utility/WebCmdlet/StreamHelper.cs | 10 +++--- 9 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index f3e04e76462..38ef89a9530 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -86,7 +86,7 @@ public WebCmdletElementCollection InputFields { EnsureHtmlParser(); - List parsedFields = new List(); + List parsedFields = new(); MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); foreach (Match field in fieldMatch) { @@ -113,7 +113,7 @@ public WebCmdletElementCollection Links { EnsureHtmlParser(); - List parsedLinks = new List(); + List parsedLinks = new(); MatchCollection linkMatch = s_linkRegex.Matches(Content); foreach (Match link in linkMatch) { @@ -140,7 +140,7 @@ public WebCmdletElementCollection Images { EnsureHtmlParser(); - List parsedImages = new List(); + List parsedImages = new(); MatchCollection imageMatch = s_imageRegex.Matches(Content); foreach (Match image in imageMatch) { @@ -186,7 +186,7 @@ protected void InitializeContent() private PSObject CreateHtmlObject(string html, string tagName) { - PSObject elementObject = new PSObject(); + PSObject elementObject = new(); elementObject.Properties.Add(new PSNoteProperty("outerHTML", html)); elementObject.Properties.Add(new PSNoteProperty("tagName", tagName)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 5d1b7c66048..f16ad99d2a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -68,7 +68,7 @@ internal static Encoding GetEncodingOrDefault(string characterSet) internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { - StringBuilder raw = new StringBuilder(); + StringBuilder raw = new(); string protocol = WebResponseHelper.GetProtocol(response); if (!string.IsNullOrEmpty(protocol)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index ba1e69c080f..b4824e3884a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -110,7 +110,7 @@ private bool TryProcessFeedStream(Stream responseStream) if (isRssOrFeed) { - XmlDocument workingDocument = new XmlDocument(); + XmlDocument workingDocument = new(); // performing a Read() here to avoid rrechecking // "rss" or "feed" items reader.Read(); @@ -145,7 +145,7 @@ private bool TryProcessFeedStream(Stream responseStream) // Mostly cribbed from Serialization.cs#GetXmlReaderSettingsForCliXml() private XmlReaderSettings GetSecureXmlReaderSettings() { - XmlReaderSettings xrs = new XmlReaderSettings(); + XmlReaderSettings xrs = new(); xrs.CheckCharacters = false; xrs.CloseInput = false; 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 744c40135ce..f4f5e9636eb 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 @@ -606,13 +606,13 @@ internal virtual void PrepareSession() if (CertificateThumbprint != null) { - X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); + 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) { - CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound); + CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); throw ex; } @@ -639,7 +639,7 @@ internal virtual void PrepareSession() if (Proxy != null) { - WebProxy webProxy = new WebProxy(Proxy); + WebProxy webProxy = new(Proxy); webProxy.BypassProxyOnLocal = false; if (ProxyCredential != null) { @@ -733,7 +733,7 @@ private Uri PrepareUri(Uri uri) && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { - UriBuilder uriBuilder = new UriBuilder(uri); + UriBuilder uriBuilder = new(uri); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan().Slice(1), "&", FormatDictionary(bodyAsDictionary)); @@ -774,7 +774,7 @@ private string FormatDictionary(IDictionary content) if (content == null) throw new ArgumentNullException(nameof(content)); - StringBuilder bodyBuilder = new StringBuilder(); + StringBuilder bodyBuilder = new(); foreach (string key in content.Keys) { if (bodyBuilder.Length > 0) @@ -984,7 +984,7 @@ private HttpMethod GetHttpMethod(WebRequestMethod method) internal virtual HttpClient GetHttpClient(bool handleRedirect) { // By default the HttpClientHandler will automatically decompress GZip and Deflate content - HttpClientHandler handler = new HttpClientHandler(); + HttpClientHandler handler = new(); handler.CookieContainer = WebSession.Cookies; // set the credentials used by this request @@ -1037,7 +1037,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) handler.SslProtocols = (SslProtocols)SslProtocol; - HttpClient httpClient = new HttpClient(handler); + HttpClient httpClient = new(handler); // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) if (TimeoutSec == 0) @@ -1284,7 +1284,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) catch (FormatException ex) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1540,8 +1540,8 @@ protected override void ProcessRecord() { string message = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.ResponseStatusCodeFailure, (int)response.StatusCode, response.ReasonPhrase); - HttpResponseException httpEx = new HttpResponseException(message, response); - ErrorRecord er = new ErrorRecord(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + HttpResponseException httpEx = new(message, response); + ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); string detailMsg = string.Empty; StreamReader reader = null; try @@ -1588,7 +1588,7 @@ protected override void ProcessRecord() response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.MovedPermanently) { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); + ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); WriteError(er); } @@ -1596,7 +1596,7 @@ protected override void ProcessRecord() } catch (HttpRequestException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); if (ex.InnerException != null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); @@ -1622,12 +1622,12 @@ protected override void ProcessRecord() } catch (CryptographicException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); + ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); ThrowTerminatingError(er); } catch (NotSupportedException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); + ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); ThrowTerminatingError(er); } } @@ -1707,7 +1707,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1716,7 +1716,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1846,7 +1846,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr string rel = match.Groups["rel"].Value; if (url != string.Empty && rel != string.Empty && !_relationLink.ContainsKey(rel)) { - Uri absoluteUri = new Uri(requestUri, url); + Uri absoluteUri = new(requestUri, url); _relationLink.Add(rel, absoluteUri.AbsoluteUri); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index e0c60ca8f3e..0af97b061a9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -27,7 +27,7 @@ public class ConvertFromJsonCommand : Cmdlet /// /// InputObjectBuffer buffers all InputObject contents available in the pipeline. /// - private readonly List _inputObjectBuffer = new List(); + private readonly List _inputObjectBuffer = new(); /// /// Returned data structure is a Hashtable instead a CustomPSObject. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 3d35cc3c7ce..5133bf85ea7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -29,7 +29,7 @@ public class ConvertToJsonCommand : PSCmdlet private const int maxDepthAllowed = 100; - private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancellationSource = new(); /// /// Gets or sets the Depth property. @@ -93,7 +93,7 @@ protected override void BeginProcessing() } } - private readonly List _inputObjects = new List(); + private readonly List _inputObjects = new(); /// /// Caching the input objects for the command. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 7e5a4ba6d63..9f1d2b1c8a2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -344,7 +344,7 @@ private static ICollection PopulateFromJArray(JArray list, out ErrorReco private static Hashtable PopulateHashTableFromJDictionary(JObject entries, out ErrorRecord error) { error = null; - Hashtable result = new Hashtable(entries.Count); + Hashtable result = new(entries.Count); foreach (var entry in entries) { // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject @@ -708,7 +708,7 @@ private static void AppendPsProperties(PSObject psObj, IDictionary receiver, int /// private static object ProcessDictionary(IDictionary dict, int depth, in ConvertToJsonContext context) { - Dictionary result = new Dictionary(dict.Count); + Dictionary result = new(dict.Count); foreach (DictionaryEntry entry in dict) { @@ -745,7 +745,7 @@ private static object ProcessDictionary(IDictionary dict, int depth, in ConvertT /// private static object ProcessEnumerable(IEnumerable enumerable, int depth, in ConvertToJsonContext context) { - List result = new List(); + List result = new(); foreach (object o in enumerable) { @@ -765,7 +765,7 @@ private static object ProcessEnumerable(IEnumerable enumerable, int depth, in Co /// private static object ProcessCustomObject(object o, int depth, in ConvertToJsonContext context) { - Dictionary result = new Dictionary(); + Dictionary result = new(); Type t = o.GetType(); foreach (FieldInfo info in t.GetFields(BindingFlags.Public | BindingFlags.Instance)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index a730c043216..2ea29e73fa3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -131,9 +131,9 @@ internal static string PlatformName if (s_windowsUserAgent == null) { // find the version in the windows operating system description - Regex pattern = new Regex(@"\d+(\.\d+)+"); + Regex pattern = new(@"\d+(\.\d+)+"); string versionText = pattern.Match(OS).Value; - Version windowsPlatformversion = new Version(versionText); + Version windowsPlatformversion = new(versionText); s_windowsUserAgent = $"Windows NT {windowsPlatformversion.Major}.{windowsPlatformversion.Minor}"; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index a1073234867..0813faf9258 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -219,7 +219,7 @@ private void Initialize() { long totalLength = 0; byte[] buffer = new byte[StreamHelper.ChunkSize]; - ProgressRecord record = new ProgressRecord(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); + ProgressRecord record = new(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); for (int read = 1; read > 0; totalLength += read) { if (_ownerCmdlet != null) @@ -284,7 +284,7 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, Task copyTask = input.CopyToAsync(output, cancellationToken); - ProgressRecord record = new ProgressRecord( + ProgressRecord record = new( ActivityId, WebCmdletStrings.WriteRequestProgressActivity, WebCmdletStrings.WriteRequestProgressStatus); @@ -322,13 +322,13 @@ internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet c { // If the web cmdlet should resume, append the file instead of overwriting. FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; - using FileStream output = new FileStream(filePath, fileMode, FileAccess.Write, FileShare.Read); + using FileStream output = new(filePath, fileMode, FileAccess.Write, FileShare.Read); WriteToStream(stream, output, cmdlet, cancellationToken); } private static string StreamToString(Stream stream, Encoding encoding) { - StringBuilder result = new StringBuilder(capacity: ChunkSize); + StringBuilder result = new(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); int useBufferSize = 64; @@ -410,7 +410,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) return result; } - private static readonly Regex s_metaexp = new Regex( + private static readonly Regex s_metaexp = new( @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase );