From c8bd8f0143518f1a1f66f0146a7db0ab1b919482 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Tue, 7 Jul 2020 00:04:03 +0100 Subject: [PATCH 01/11] Autofix RCS1118 --- .../CimInvokeCimMethod.cs | 2 +- .../CommonUtils.cs | 2 +- .../PdhHelper.cs | 2 +- .../commands/management/CIMHelper.cs | 4 +-- .../commands/utility/AddType.cs | 2 +- .../FormatAndOutput/OutGridView/TableView.cs | 2 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 4 +-- .../out-printer/PrinterLineOutput.cs | 6 ++-- .../utility/ImplicitRemotingCommands.cs | 16 +++++----- .../utility/ImportPowerShellDataFile.cs | 6 ++-- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../WindowsTaskbarJumpList/TaskbarJumpList.cs | 4 +-- .../host/msh/ConsoleControl.cs | 2 +- .../host/msh/ConsoleHost.cs | 4 +-- .../msh/ConsoleHostUserInterfacePrompt.cs | 2 +- ...ConsoleHostUserInterfacePromptForChoice.cs | 2 +- .../host/msh/PendingProgress.cs | 2 +- .../Eventing/Reader/NativeWrapper.cs | 4 +-- .../security/CertificateProvider.cs | 32 +++++++++---------- .../ConfigProvider.cs | 2 +- src/Microsoft.WSMan.Management/CredSSP.cs | 8 ++--- .../DscSupport/CimDSCParser.cs | 2 +- .../common/BaseOutputtingCommand.cs | 2 +- .../common/DisplayDatabase/XmlLoaderBase.cs | 4 +-- .../typeDataXmlLoader_Table.cs | 2 +- .../common/FormatViewGenerator_Table.cs | 2 +- .../common/FormatViewManager.cs | 2 +- .../PseudoParameterBinder.cs | 2 +- .../engine/EnumMinimumDisambiguation.cs | 4 +-- .../engine/EventManager.cs | 4 +-- .../ExperimentalFeature.cs | 6 ++-- .../engine/Modules/ModuleCmdletBase.cs | 2 +- .../engine/Modules/ModuleIntrinsics.cs | 2 +- .../engine/Modules/RemoteDiscoveryHelper.cs | 4 +-- .../engine/MshCommandRuntime.cs | 2 +- .../engine/NativeCommandParameterBinder.cs | 2 +- .../engine/SessionStateContainer.cs | 4 +-- .../engine/debugger/debugger.cs | 4 +-- .../hostifaces/InternalHostUserInterface.cs | 4 +-- .../engine/parser/TypeInferenceVisitor.cs | 2 +- .../remoting/client/remoterunspaceinfo.cs | 4 +-- .../remoting/commands/CustomShellCommands.cs | 2 +- .../remoting/commands/DisconnectPSSession.cs | 2 +- .../commands/NewPSSessionConfigurationFile.cs | 4 +-- .../remoting/commands/PushRunspaceCommand.cs | 12 +++---- .../remoting/commands/remotingcommandutil.cs | 2 +- .../remoting/common/RemoteSessionNamedPipe.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 4 +-- .../common/WireDataFormat/EncodeAndDecode.cs | 4 +-- .../engine/remoting/common/fragmentor.cs | 8 ++--- .../remoting/fanin/PriorityCollection.cs | 4 +-- .../remoting/fanin/WSManPluginFacade.cs | 2 +- .../remoting/server/ServerMethodExecutor.cs | 2 +- .../server/ServerRunspacePoolDriver.cs | 4 +-- .../remoting/server/serverremotesession.cs | 2 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 2 +- .../help/CommandHelpProvider.cs | 2 +- .../help/HelpCommands.cs | 2 +- .../help/HelpCommentsParser.cs | 2 +- .../help/PSClassHelpProvider.cs | 4 +-- .../help/UpdatableHelpCommandBase.cs | 2 +- .../help/UpdatableHelpSystem.cs | 4 +-- .../namespaces/FileSystemProvider.cs | 28 ++++++++-------- .../namespaces/RegistryProvider.cs | 2 +- .../security/CatalogHelper.cs | 4 +-- .../utils/IObjectWriter.cs | 2 +- test/xUnit/csharp/test_NamedPipe.cs | 2 +- test/xUnit/csharp/test_Utils.cs | 4 +-- 68 files changed, 142 insertions(+), 142 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index ba82ff9e432..20b0a211f2c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -374,7 +374,7 @@ private CimMethodParametersCollection CreateParametersCollection( { string parameterName = enumerator.Key.ToString(); - CimFlags parameterFlags = CimFlags.In; + const CimFlags parameterFlags = CimFlags.In; object parameterValue = GetBaseObject(enumerator.Value); DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4, diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index bd99ef7aff2..0b13d81d98f 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -57,7 +57,7 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou try { - uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; + const uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; uint LANGID = (uint)GetUserDefaultLangID(); uint langError = (uint)Marshal.GetLastWin32Error(); if (langError != 0) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 130a7f41804..2e0e7cfe57f 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1061,7 +1061,7 @@ public uint GetValidPaths(string machineName, ref StringCollection instances, ref StringCollection validPaths) { - uint res = 0; + const uint res = 0; PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); pathElts.MachineName = machineName; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index 559af13127b..b954e502ff8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -85,7 +85,7 @@ internal static string WqlQueryAll(string from) try { var type = typeof(T); - var binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + const BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; T rv = new T(); using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName))) @@ -144,7 +144,7 @@ internal static string WqlQueryAll(string from) if (instances != null) { var type = typeof(T); - var binding = BindingFlags.Public | BindingFlags.Instance; + const BindingFlags binding = BindingFlags.Public | BindingFlags.Instance; foreach (var instance in instances) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 4f7185a7e85..3c2c4e055db 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -903,7 +903,7 @@ private CommandLineArguments ParseCompilerOption(IEnumerable args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; - string additionalReferenceDirectories = null; + const string additionalReferenceDirectories = null; switch (Language) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index dc967889e69..73e4176e7b5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -197,7 +197,7 @@ private void FilterActiveAssociationList(List nMax) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index a0225c8ea6a..364233669c4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -472,7 +472,7 @@ private byte[] ConvertToBytes(object inputObject) /// Offset in the file. private void WriteHexadecimal(Span inputBytes, string path, long offset) { - var bytesPerObject = 16; + const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject @@ -494,7 +494,7 @@ private void WriteHexadecimal(Span inputBytes, string path, long offset) /// private void WriteHexadecimal(Span inputBytes, long offset, string label) { - var bytesPerObject = 16; + const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 5616a7fa436..64788d2b2a8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -187,9 +187,9 @@ private void VerifyFont(Graphics g) // we compute the length of two strings, one made of "large" characters // one made of "narrow" ones. If they are the same length, we assume that // the font is fixed pitch. - string large = "ABCDEF"; + const string large = "ABCDEF"; float wLarge = g.MeasureString(large, _printFont).Width / large.Length; - string narrow = ".;'}l|"; + const string narrow = ".;'}l|"; float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length; if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F) @@ -229,7 +229,7 @@ private void pd_PrintPage(object sender, PrintPageEventArgs ev) // on the first page we have to initialize the metrics for LineOutput // work out the number of columns per page assuming fixed pitch font - string s = "ABCDEF"; + const string s = "ABCDEF"; float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length; float columnsPerPage = ev.MarginBounds.Width / w; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index feeb0cd091b..e94e94fa2a8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -545,7 +545,7 @@ internal ErrorDetails GetErrorDetails(string errorId, params object[] args) private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() { - string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; + const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; ErrorDetails details = this.GetErrorDetails(errorId); @@ -566,7 +566,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorMalformedDataFromRemoteCommand"; + const string errorId = "ErrorMalformedDataFromRemoteCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -587,7 +587,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames throw PSTraceSource.NewArgumentNullException(nameof(commandNames)); } - string errorId = "ErrorCommandSkippedBecauseOfShadowing"; + const string errorId = "ErrorCommandSkippedBecauseOfShadowing"; ErrorDetails details = this.GetErrorDetails(errorId, commandNames); @@ -608,7 +608,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedNonRequestedCommand"; + const string errorId = "ErrorSkippedNonRequestedCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -629,7 +629,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } - string errorId = "ErrorSkippedNonRequestedTypeDefinition"; + const string errorId = "ErrorSkippedNonRequestedTypeDefinition"; ErrorDetails details = this.GetErrorDetails(errorId, typeName); @@ -650,7 +650,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedUnsafeCommandName"; + const string errorId = "ErrorSkippedUnsafeCommandName"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -757,7 +757,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) throw PSTraceSource.NewArgumentNullException(nameof(aliasName)); } - string errorId = "ErrorCouldntResolveAlias"; + const string errorId = "ErrorCouldntResolveAlias"; ErrorDetails details = this.GetErrorDetails(errorId, aliasName); @@ -778,7 +778,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorNoResultsFromRemoteEnd"; + const string errorId = "ErrorNoResultsFromRemoteEnd"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 694e82686be..9195e49052b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -78,8 +78,8 @@ protected override void ProcessRecord() private void WritePathNotFoundError(string path) { - var errorId = "PathNotFound"; - var errorCategory = ErrorCategory.InvalidArgument; + const string errorId = "PathNotFound"; + const ErrorCategory errorCategory = ErrorCategory.InvalidArgument; var errorMessage = string.Format(UtilityCommonStrings.PathDoesNotExist, path); var exception = new ArgumentException(errorMessage); var errorRecord = new ErrorRecord(exception, errorId, errorCategory, path); @@ -88,7 +88,7 @@ private void WritePathNotFoundError(string path) private void WriteInvalidDataFileError(string resolvedPath, string errorId) { - var errorCategory = ErrorCategory.InvalidData; + const ErrorCategory errorCategory = ErrorCategory.InvalidData; var errorMessage = string.Format(UtilityCommonStrings.CouldNotParseAsPowerShellDataFile, resolvedPath); var exception = new InvalidOperationException(errorMessage); var errorRecord = new ErrorRecord(exception, errorId, errorCategory, resolvedPath); 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 94dde3c00fb..488dc068380 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 @@ -1829,7 +1829,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr // we only support the URL in angle brackets and `rel`, other attributes are ignored // user can still parse it themselves via the Headers property - string pattern = "<(?.*?)>;\\s*rel=(\"?)(?.*?)\\1[^\\w -.]?"; + const string pattern = "<(?.*?)>;\\s*rel=(\"?)(?.*?)\\1[^\\w -.]?"; IEnumerable links; if (response.Headers.TryGetValues("Link", out links)) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 5b7572c94b2..30e69cf1f05 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -59,8 +59,8 @@ private static void CreateElevatedEntry(string title) // Check startupInfo first to know if the current shell is interactive and owns a window before proceeding // This check is fast (less than 1ms) and allows for quick-exit GetStartupInfo(out StartUpInfo startupInfo); - var STARTF_USESHOWWINDOW = 0x00000001; - var SW_HIDE = 0; + const int STARTF_USESHOWWINDOW = 0x00000001; + const int SW_HIDE = 0; if (((startupInfo.dwFlags & STARTF_USESHOWWINDOW) == 1) && (startupInfo.wShowWindow != SW_HIDE)) { string cmdPath = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 6159e349497..bbbd60fa7a5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2494,7 +2494,7 @@ internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) internal static string GetConsoleWindowTitle() { const int MaxWindowTitleLength = 1024; - DWORD bufferSize = MaxWindowTitleLength; + const DWORD bufferSize = MaxWindowTitleLength; DWORD result; StringBuilder consoleTitle = new StringBuilder((int)bufferSize); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 206a7e44e7f..ca5e3e8a722 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1770,7 +1770,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, } else { - string shellId = "Microsoft.PowerShell"; + const string shellId = "Microsoft.PowerShell"; // If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc // are loaded so that they are trusted. (Validation of their signatures is done in F&O) @@ -2021,7 +2021,7 @@ internal static string EscapeSingleQuotes(string str) private void WriteErrorLine(string line) { - ConsoleColor fg = ConsoleColor.Red; + const ConsoleColor fg = ConsoleColor.Red; ConsoleColor bg = UI.RawUI.BackgroundColor; UI.WriteLine(fg, bg, line); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 0afe5f987d8..3171d71533c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -148,7 +148,7 @@ public override string fieldPrompt = null; fieldPrompt = desc.Name; - bool fieldEchoOnPrompt = true; + const bool fieldEchoOnPrompt = true; // FieldDescription.ParameterAssemblyFullName never returns null. But this is // defense in depth. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index 0dfe3f63739..61b2d090fc7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -301,7 +301,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, int lineLenMax = RawUI.WindowSize.Width - 1; int lineLen = 0; - string choiceTemplate = "[{0}] {1} "; + const string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 2ca795447d0..c1ffc24bc96 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -836,7 +836,7 @@ internal override { nodesCompressed = 0; - int age = 0; + const int age = 0; while (true) { diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 8858b067f8a..5ffbb6711ac 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -958,7 +958,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; try { @@ -1124,7 +1124,7 @@ public static string EvtRenderBookmark(EventLogHandle eventHandle) IntPtr buffer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; try { diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index d0a589bb1cb..c94882e0569 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -636,7 +636,7 @@ private static Regex CertPathRegex { if (s_certPathRegex == null) { - RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; + const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; s_certPathRegex = new Regex(certPathPattern, options); } } @@ -723,7 +723,7 @@ protected override void RemoveItem( string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } @@ -748,7 +748,7 @@ protected override void RemoveItem( if (fUserContext) { string message = CertificateProviderStrings.CannotDeleteUserStore; - string errorId = "CannotDeleteUserStore"; + const string errorId = "CannotDeleteUserStore"; ThrowInvalidOperation(errorId, message); } @@ -758,7 +758,7 @@ protected override void RemoveItem( else // other container than a store { string message = CertificateProviderStrings.CannotRemoveContainer; - string errorId = "CannotRemoveContainer"; + const string errorId = "CannotRemoveContainer"; ThrowInvalidOperation(errorId, message); } } @@ -830,7 +830,7 @@ protected override void MoveItem( if (isContainer) { string message = CertificateProviderStrings.CannotMoveContainer; - string errorId = "CannotMoveContainer"; + const string errorId = "CannotMoveContainer"; ThrowInvalidOperation(errorId, message); } @@ -847,7 +847,7 @@ protected override void MoveItem( else { string message = CertificateProviderStrings.InvalidDestStore; - string errorId = "InvalidDestStore"; + const string errorId = "InvalidDestStore"; ThrowInvalidOperation(errorId, message); } } @@ -859,14 +859,14 @@ protected override void MoveItem( if (!string.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveCrossContext; - string errorId = "CannotMoveCrossContext"; + const string errorId = "CannotMoveCrossContext"; ThrowInvalidOperation(errorId, message); } if (string.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveToSameStore; - string errorId = "CannotMoveToSameStore"; + const string errorId = "CannotMoveToSameStore"; ThrowInvalidOperation(errorId, message); } @@ -880,7 +880,7 @@ protected override void MoveItem( string.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } } @@ -964,7 +964,7 @@ protected override void NewItem( if (pathElements.Length != 2) { string message = CertificateProviderStrings.CannotCreateItem; - string errorId = "CannotCreateItem"; + const string errorId = "CannotCreateItem"; ThrowInvalidOperation(errorId, message); } @@ -974,11 +974,11 @@ protected override void NewItem( if (fUserContext) { string message = CertificateProviderStrings.CannotCreateUserStore; - string errorId = "CannotCreateUserStore"; + const string errorId = "CannotCreateUserStore"; ThrowInvalidOperation(errorId, message); } - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; @@ -1418,7 +1418,7 @@ protected override void InvokeDefaultAction(string path) { path = NormalizePath(path); string action = CertificateProviderStrings.Action_Invoke; - string certmgr = "certmgr.msc"; + const string certmgr = "certmgr.msc"; string certPath = System.IO.Path.Combine( System.Environment.ExpandEnvironmentVariables("%windir%"), "system32"); @@ -1778,7 +1778,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat certContext = store.GetNextCert(certContext); } // remove the cert store - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | @@ -1799,7 +1799,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat CultureInfo.CurrentCulture, CertificateProviderStrings.RemoveStoreTemplate, storeName); - string errorId = "CannotRemoveSystemStore"; + const string errorId = "CannotRemoveSystemStore"; ThrowInvalidOperation(errorId, message); } } @@ -2834,7 +2834,7 @@ internal static bool CertContainsEku(X509Certificate2 cert, List 0) diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 52c4f4e921d..7906534cd75 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -234,7 +234,7 @@ private void DeleteUserDelegateSettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -515,7 +515,7 @@ private void EnableClientSideSettings() return; } - string newxmlcontent = @"true"; + const string newxmlcontent = @"true"; try { XmlDocument xmldoc = new XmlDocument(); @@ -633,7 +633,7 @@ private void UpdateCurrentUserRegistrySettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -834,7 +834,7 @@ protected override void BeginProcessing() } // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". - string applicationname = "wsman"; + const string applicationname = "wsman"; string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 58fc81715bb..22560e72431 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -41,7 +41,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) { - string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; + const string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; powerShell.AddScript(script); powerShell.AddArgument(targetType); diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index bb8305b2fdc..e42c947bced 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -181,7 +181,7 @@ private FormatShape ActiveFormattingShape { // we assume that the format context // contains the information - FormatShape shape = FormatShape.Table; // default + const FormatShape shape = FormatShape.Table; // default FormatOutputContext foc = this.FormatContext; if (foc == null || foc.Data.shapeInfo == null) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 02d60731e43..2bc400ba542 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -378,7 +378,7 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML tag differ in case only {0} {1}"; + const string fmtString = "XML tag differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, n.Name, s)); match = true; @@ -420,7 +420,7 @@ internal bool MatchAttributeName(XmlAttribute a, string s) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML attribute differ in case only {0} {1}"; + const string fmtString = "XML attribute differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s)); return true; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index acc60a3e3e5..d5f549b6a72 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -353,7 +353,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde using (this.StackFrame(rowEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 - bool columnEntriesNodeFound = false; // cardinality 1 + const bool columnEntriesNodeFound = false; // cardinality 1 bool multiLineFound = false; // cardinality 0..1 TableRowDefinition trd = new TableRowDefinition(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index ab4912c8838..0183384aae0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -137,7 +137,7 @@ private void FilterActiveAssociationList() // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default - int nMax = 10; + const int nMax = 10; if (activeAssociationList.Count > nMax) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index aca38f8994b..19803360799 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -234,7 +234,7 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string msg = null; bool foundValidViews = false; string formatTypeName = null; - string separator = ", "; + const string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index d19a4b9bddb..5b002d0b397 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -261,7 +261,7 @@ public static class StaticParameterBinder /// The StaticBindingResult that represents the binding. public static StaticBindingResult BindCommand(CommandAst commandAst) { - bool resolve = true; + const bool resolve = true; return BindCommand(commandAst, resolve); } diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 543d920418f..0eed3c7d2f8 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -85,7 +85,7 @@ internal static string EnumDisambiguate(string text, Type enumType) } // No special cases match, throw error for multiple matches. StringBuilder matchListSB = new StringBuilder(namesWithMatchingPrefix[0]); - string separator = ", "; + const string separator = ", "; for (int i = 1; i < namesWithMatchingPrefix.Count; i++) { matchListSB.Append(separator); @@ -106,7 +106,7 @@ internal static string EnumDisambiguate(string text, Type enumType) internal static string EnumAllValues(Type enumType) { string[] names = Enum.GetNames(enumType); - string separator = ", "; + const string separator = ", "; StringBuilder returnValue = new StringBuilder(); if (names.Length != 0) { diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index e2cb546376c..126143fd982 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -680,7 +680,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s } // Retrieve the event from the object - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(eventName, bindingFlags); // If we can't find the event, throw an exception @@ -844,7 +844,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) Type sourceType = subscriber.SourceObject as Type ?? subscriber.SourceObject.GetType(); - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(subscriber.EventName, bindingFlags); if ((eventInfo != null) && (existingSubscriber != null)) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index e44ea07962c..bad49105d49 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -345,14 +345,14 @@ internal static void ValidateArguments(string experimentName, ExperimentAction e { if (string.IsNullOrEmpty(experimentName)) { - string paramName = nameof(experimentName); + const string paramName = nameof(experimentName); throw PSTraceSource.NewArgumentNullException(paramName, Metadata.ArgumentNullOrEmpty, paramName); } if (experimentAction == ExperimentAction.None) { - string paramName = nameof(experimentAction); - string invalidMember = nameof(ExperimentAction.None); + const string paramName = nameof(experimentAction); + const string invalidMember = nameof(ExperimentAction.None); string validMembers = StringUtil.Format("{0}, {1}", ExperimentAction.Hide, ExperimentAction.Show); throw PSTraceSource.NewArgumentException(paramName, Metadata.InvalidEnumArgument, invalidMember, paramName, validMembers); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index f1f8aaff1f7..09b6514af06 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1140,7 +1140,7 @@ internal static Version GetMaximumVersion(string stringVersion) else { // If first conversion fails, try to convert * to maximum version - string maxRange = "999999999"; + const string maxRange = "999999999"; if (stringVersion[stringVersion.Length - 1] == '*') { stringVersion = stringVersion.Substring(0, stringVersion.Length - 1); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index b20e11e4745..db1191ed1d7 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -705,7 +705,7 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) #if UNIX StringComparison strcmp = StringComparison.Ordinal; #else - StringComparison strcmp = StringComparison.OrdinalIgnoreCase; + const StringComparison strcmp = StringComparison.OrdinalIgnoreCase; #endif // We must check modulePath (e.g. /path/to/module/module.psd1) against several possibilities: diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 015b2bb72d2..9fd55c287b6 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -31,7 +31,7 @@ internal class RemoteDiscoveryHelper private static Collection RehydrateHashtableKeys(PSObject pso, string propertyName) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue(pso, propertyName, rehydrationFlags); if (hashtable == null) @@ -53,7 +53,7 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleInfo) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; string name = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Name", rehydrationFlags); string path = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Path", rehydrationFlags); diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index eea82e1ab65..dd6ea513361 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1734,7 +1734,7 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - bool hasSecurityImpact = false; + const bool hasSecurityImpact = false; return DoShouldContinue(query, caption, hasSecurityImpact, false, ref yesToAll, ref noToAll); } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 0091596a443..d275a3b2753 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -260,7 +260,7 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array /// Bare, SingleQuoted, or DoubleQuoted. private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) { - var argExpanded = false; + const bool argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index f4f2a46d2a5..2093dce2472 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4796,7 +4796,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (languageMode.HasValue && (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage)) { - var psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName; + const string psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName; ps.Runspace = session.Runspace; ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName); var result = ps.Invoke(); @@ -4826,7 +4826,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses } else { - string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; + const string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; ps.AddScript(remoteScript); } diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 8fed757e725..eafbb38207f 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -4474,13 +4474,13 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; - string processPartPattern = "{0}[{1}:{2}]:{3}"; + const string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", DebuggerStrings.NestedRunspaceDebuggerPromptProcessName, @"$($PID)", @""""); - string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; + const string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.EscapeSingleQuotedStringContent(_runspace.Name) + "]: '" + " + " + locationPart; // Get the command prompt from the wrapped debugger. diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 8432b4432d0..315fa1b9239 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -927,7 +927,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); - char newLine = '\n'; + const char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); @@ -943,7 +943,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); - string choiceTemplate = "[{0}] {1} "; + const string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 59cf5348cc8..16e0dc4bd82 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1218,7 +1218,7 @@ bool IsInPropertyArgument(object o) } var previousPipelineElement = GetPreviousPipelineCommand(commandAst); - var typeName = "Microsoft.PowerShell.Commands.GroupInfo"; + const string typeName = "Microsoft.PowerShell.Commands.GroupInfo"; var members = new List(); foreach (var prevType in InferTypes(previousPipelineElement)) { diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index 1a975f5a785..f5ffdf03dfd 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -208,7 +208,7 @@ public Runspace Runspace public override string ToString() { // PSSession is a PowerShell type name and so should not be localized. - string formatString = "[PSSession]{0}"; + const string formatString = "[PSSession]{0}"; return StringUtil.Format(formatString, Name); } @@ -349,7 +349,7 @@ private string GetTransportName() /// Display shell name. private string GetDisplayShellName(string shell) { - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = shell.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); return (index == 0) ? shell.Substring(shellPrefix.Length) : shell; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 71985462fc5..7408eeeef4f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -798,7 +798,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d destConfigFilePath = null; StringBuilder initParameters = new StringBuilder(); - bool assemblyAndTypeTokensSet = false; + const bool assemblyAndTypeTokensSet = false; // DISC endpoint if (Path != null) diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 0b9cfeb2d6e..aaba4a9bd4f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -346,7 +346,7 @@ private bool ValidateIdleTimeout(PSSession session) { int idleTimeout = session.Runspace.ConnectionInfo.IdleTimeout; int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout; - int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; + const int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout && (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout)) diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 4fe43f53cee..4d14af98914 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -857,7 +857,7 @@ protected override void ProcessRecord() { if (Full) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } } @@ -1621,7 +1621,7 @@ protected override void ProcessRecord() // Modules to import if (_modulesToImport == null) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } else diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index a7751e0138d..ba3a967f779 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -798,8 +798,8 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { return info.InstanceId == remoteRunspaceId; }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; + const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; + const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId); @@ -814,8 +814,8 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { return info.Id == sessionId; }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; + const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; + const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId; string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId); @@ -831,8 +831,8 @@ private RemoteRunspace GetRunspaceMatchingName(string name) // doing case-insensitive match for session name return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; + const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; + const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName; string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName; return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name); diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index ad233ccb481..9543114b5f0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -87,7 +87,7 @@ internal static void CheckRemotingCmdletPrerequisites() return; #else bool notSupported = true; - string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; + const string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; CheckHostRemotingPrerequisites(); diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 3a75567c10f..7add4e1688b 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -1303,7 +1303,7 @@ public ContainerSessionNamedPipeClient( protected override NamedPipeClientStream DoConnect(int timeout) { // Create pipe flags. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; + const uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 7f46151a857..52f95bb7faf 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2053,7 +2053,7 @@ internal int StartSSHProcess( #if UNIX string sshCommand = "ssh"; #else - string sshCommand = "ssh.exe"; + const string sshCommand = "ssh.exe"; #endif var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) @@ -2627,7 +2627,7 @@ private static Process CreateProcessWithRedirectedStd( private static SafePipeHandle GetNamedPipeHandle(string pipeName) { // Create pipe flags for asynchronous pipes. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; + const uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; // We want an inheritable handle. PlatformInvokes.SECURITY_ATTRIBUTES securityAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES(); diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index 85ba02b2e7b..83f69b6f951 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1198,7 +1198,7 @@ internal static RemoteDataObject GenerateRunspacePoolStateInfo( { // If Reason is of not type IContainsErrorRecord, a new ErrorRecord is // created using this errorId - string errorId = "RemoteRunspaceStateInfoReason"; + const string errorId = "RemoteRunspaceStateInfoReason"; PSNoteProperty exceptionProperty = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1517,7 +1517,7 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn { // If Reason is of not type IContainsErrorRecord, // a new ErrorRecord is created using this errorId - string errorId = "RemotePSInvocationStateInfoReason"; + const string errorId = "RemotePSInvocationStateInfoReason"; PSNoteProperty exceptionProperty = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 2ebe434ea04..e093803a439 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -205,10 +205,10 @@ internal byte[] Blob /// internal byte[] GetBytes() { - int objectIdSize = 8; // number of bytes of long - int fragmentIdSize = 8; // number of bytes of long - int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl - int blobLengthSize = 4; // number of bytes of int + const int objectIdSize = 8; // number of bytes of long + const int fragmentIdSize = 8; // number of bytes of long + const int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl + const int blobLengthSize = 4; // number of bytes of int int totalLength = objectIdSize + fragmentIdSize + flagsSize + blobLengthSize + BlobLength; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 8ddd0eb8cb1..30de10f1f7b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -163,8 +163,8 @@ Verify arrays and dataToBeSent objects before referencing. */ if (_dataSyncObjects != null && _dataToBeSent != null) { - int promptResponseIndex = (int)DataPriorityType.PromptResponse; - int defaultIndex = (int)DataPriorityType.Default; + const int promptResponseIndex = (int)DataPriorityType.PromptResponse; + const int defaultIndex = (int)DataPriorityType.Default; lock (_dataSyncObjects[promptResponseIndex]) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 31f0e0d268c..994d79ef75b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -521,7 +521,7 @@ public static void WSManPluginShell( // In debug builds, allow remote runspaces to wait for debugger attach if (Environment.GetEnvironmentVariable("__PSRemoteRunspaceWaitForDebugger", EnvironmentVariableTarget.Machine) != null) { - bool debuggerAttached = false; + const bool debuggerAttached = false; while (!debuggerAttached) { System.Threading.Thread.Sleep(100); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index 0c0fb0a0c42..1082aa9b2b0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -92,7 +92,7 @@ internal void ExecuteVoidMethod(RemoteHostMethodId methodId, object[] parameters Dbg.Assert(parameters != null, "Expected parameters != null"); // Use void call ID so that the call is known to not have a return value. - long callId = ServerDispatchTable.VoidCallId; + const long callId = ServerDispatchTable.VoidCallId; RemoteHostCall remoteHostCall = new RemoteHostCall(callId, methodId, parameters); // Dispatch the call but don't wait for response since the return value is void. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 10814c3ea2b..2327c14f1f2 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -2064,7 +2064,7 @@ public override bool IsActive public override void SetDebuggerStepMode(bool enabled) { // Enable both the wrapper and wrapped debuggers for debugging before setting step mode. - DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; + const DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; base.SetDebugMode(mode); _wrappedDebugger.Value.SetDebugMode(mode); @@ -2710,7 +2710,7 @@ internal void StartPowerShellCommand( powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged; powershell.SetIsNested(false); - string script = @" + const string script = @" param ($Debugger, $Commands, $output) trap { throw $_ } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 16978ff04e3..0039c6814ed 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -206,7 +206,7 @@ internal static ServerRemoteSession CreateServerRemoteSession( throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId); } - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = configurationProviderId.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); senderInfo.ConfigurationName = (index == 0) ? configurationProviderId.Substring(shellPrefix.Length) : string.Empty; ServerRemoteSession result = new ServerRemoteSession( diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 4e6d81e9208..b53404463f8 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -547,7 +547,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported"); Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type"); - PipelineResultTypes toType = PipelineResultTypes.Output; + const PipelineResultTypes toType = PipelineResultTypes.Output; PipelineResultTypes fromType; switch (commandAst.Redirections[0].FromStream) { diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index c460cc6647b..4f0ae663e32 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1252,7 +1252,7 @@ private static bool Match(string target, ICollection patterns) /// The result helpInfo objects after processing. internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { - HelpCategory categoriesHandled = (HelpCategory.Alias + const HelpCategory categoriesHandled = (HelpCategory.Alias | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand); if ((helpInfo.HelpCategory & categoriesHandled) != 0) diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index ca630180fbf..a1045e3f4f3 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -554,7 +554,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) } // categories that support -Parameter, -Role, -Functionality, -Component parameters - HelpCategory supportedCategories = + const HelpCategory supportedCategories = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand; diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 77347527ab4..56317af1f7a 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -496,7 +496,7 @@ private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, M private static void GetExampleSections(string content, out string prompt_str, out string code_str, out string remarks_str) { - string default_prompt_str = "PS > "; + const string default_prompt_str = "PS > "; var promptMatch = Regex.Match(content, "^.*?>"); prompt_str = promptMatch.Success ? promptMatch.Value : default_prompt_str; diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index ee65529a026..7963657d000 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -80,7 +80,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool else patternList.Add(target); - bool useWildCards = true; + const bool useWildCards = true; foreach (string pattern in patternList) { @@ -109,7 +109,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) } string target = helpRequest.Target; - bool useWildCards = false; + const bool useWildCards = false; PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context); diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index e9f601aba52..2aeed4294de 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -300,7 +300,7 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf } // Match wildcards - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; + const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); foreach (KeyValuePair name in s_metadataCache) diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 0a45b9a7605..99c22d78197 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -586,7 +586,7 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; + const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions); for (int i = 0; i < updatableHelpItem.Length; i++) @@ -1305,7 +1305,7 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null"); - string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; + const string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; foreach (XmlNode node in helpItemsNode.ChildNodes) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 6c91b806dfa..f61108e4b75 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -4196,7 +4196,7 @@ private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automa return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyFromSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4374,7 +4374,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf wStream = AlternateDataStreamUtilities.CreateFileStream(destinationFile.FullName, streamName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); } #endif - long fragmentSize = FILETRANSFERSIZE; + const long fragmentSize = FILETRANSFERSIZE; long copiedSoFar = 0; long currentIndex = 0; @@ -4507,7 +4507,7 @@ private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automatio { if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4625,7 +4625,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath WriteProgress(progress); // 4MB gives the best results without spiking the resources on the remote connection. - int fragmentSize = FILETRANSFERSIZE; + const int fragmentSize = FILETRANSFERSIZE; byte[] fragment = null; int iteration = 0; bool success = false; @@ -6774,7 +6774,7 @@ public IContentWriter GetContentWriter(string path) bool usingByteEncoding = false; bool streamTypeSpecified = false; Encoding encoding = ClrFacade.GetDefaultEncoding(); - FileMode filemode = FileMode.OpenOrCreate; + const FileMode filemode = FileMode.OpenOrCreate; string streamName = null; bool suppressNewline = false; @@ -8282,10 +8282,10 @@ internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) #if !UNIX private static bool WinIsSameFileSystemItem(string pathOne, string pathTwo) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sfOne = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathOne, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) using (var sfTwo = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathTwo, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) @@ -8321,10 +8321,10 @@ internal static bool GetInodeData(string path, out System.ValueTuple inodeData) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sf = AlternateDataStreamUtilities.NativeMethods.CreateFile(path, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) { @@ -8610,7 +8610,7 @@ internal static List GetStreams(string path) findStreamData.Name = findStreamData.Name.Substring(1); // And trailing :$DATA (as long as it's not the default data stream) - string dataStream = ":$DATA"; + const string dataStream = ":$DATA"; if (!string.Equals(findStreamData.Name, dataStream, StringComparison.OrdinalIgnoreCase)) { findStreamData.Name = findStreamData.Name.Replace(dataStream, string.Empty); diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index cb2963f40c7..6ca03fe0410 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -4110,7 +4110,7 @@ private string GetLocalizedDefaultToken() { // This shouldn't be localized as it will break scripts - string defaultValueName = "(default)"; + const string defaultValueName = "(default)"; return defaultValueName; } diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 050c373af74..0167670d3f8 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -414,8 +414,8 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) _cmdlet.ThrowTerminatingError(errorRecord); } - DWORD GENERIC_READ = 0x80000000; - DWORD OPEN_EXISTING = 3; + const DWORD GENERIC_READ = 0x80000000; + const DWORD OPEN_EXISTING = 3; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 5a6afad9514..0516fda50bb 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -161,7 +161,7 @@ public override void Flush() public override int Write(object obj) { - int numberOfObjectsWritten = 1; + const int numberOfObjectsWritten = 1; _count += numberOfObjectsWritten; return numberOfObjectsWritten; } diff --git a/test/xUnit/csharp/test_NamedPipe.cs b/test/xUnit/csharp/test_NamedPipe.cs index 1ee50036fc0..1174799fd95 100644 --- a/test/xUnit/csharp/test_NamedPipe.cs +++ b/test/xUnit/csharp/test_NamedPipe.cs @@ -31,7 +31,7 @@ public void TestCustomPipeNameCreation() [Fact] public void TestCustomPipeNameCreationTooLongOnNonWindows() { - var longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; + const string longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; if (!Platform.IsWindows) { diff --git a/test/xUnit/csharp/test_Utils.cs b/test/xUnit/csharp/test_Utils.cs index cda3d5741f4..454d3c3fb37 100644 --- a/test/xUnit/csharp/test_Utils.cs +++ b/test/xUnit/csharp/test_Utils.cs @@ -59,7 +59,7 @@ public static void TestHistoryStack() [Fact] public static void TestBoundedStack() { - int capacity = 20; + const int capacity = 20; var boundedStack = new BoundedStack(capacity); Assert.Throws(() => boundedStack.Pop()); @@ -116,7 +116,7 @@ public static void TestConvertToJsonWithEnum() public static void TestConvertToJsonWithoutCompress() { var context = new JsonObject.ConvertToJsonContext(maxDepth: 1, enumsAsStrings: true, compressOutput: false); - string expected = @"{ + const string expected = @"{ ""type"": ""Alias"" }"; Hashtable hash = new Hashtable { From f57719ec6aaacca8254196887a0112d6c996846b Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sun, 19 Jul 2020 17:11:28 +0100 Subject: [PATCH 02/11] Cleanup after RCS1118 autofix --- .../WindowsTaskbarJumpList/TaskbarJumpList.cs | 4 ++-- .../engine/NativeCommandParameterBinder.cs | 2 +- .../engine/remoting/common/RunspaceConnectionInfo.cs | 2 +- .../engine/remoting/fanin/WSManPluginFacade.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 30e69cf1f05..6ac50fa0e3e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -59,8 +59,8 @@ private static void CreateElevatedEntry(string title) // Check startupInfo first to know if the current shell is interactive and owns a window before proceeding // This check is fast (less than 1ms) and allows for quick-exit GetStartupInfo(out StartUpInfo startupInfo); - const int STARTF_USESHOWWINDOW = 0x00000001; - const int SW_HIDE = 0; + const uint STARTF_USESHOWWINDOW = 0x00000001; + const ushort SW_HIDE = 0; if (((startupInfo.dwFlags & STARTF_USESHOWWINDOW) == 1) && (startupInfo.wShowWindow != SW_HIDE)) { string cmdPath = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe"); diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index d275a3b2753..e77ac6d5192 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -260,7 +260,7 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array /// Bare, SingleQuoted, or DoubleQuoted. private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) { - const bool argExpanded = false; + bool argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 52f95bb7faf..d74986b674f 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2051,7 +2051,7 @@ internal int StartSSHProcess( { string filePath = string.Empty; #if UNIX - string sshCommand = "ssh"; + const string sshCommand = "ssh"; #else const string sshCommand = "ssh.exe"; #endif diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 994d79ef75b..31f0e0d268c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -521,7 +521,7 @@ public static void WSManPluginShell( // In debug builds, allow remote runspaces to wait for debugger attach if (Environment.GetEnvironmentVariable("__PSRemoteRunspaceWaitForDebugger", EnvironmentVariableTarget.Machine) != null) { - const bool debuggerAttached = false; + bool debuggerAttached = false; while (!debuggerAttached) { System.Threading.Thread.Sleep(100); From 453ed69c628201c42a00d68802a6381408e3bc8c Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sun, 19 Jul 2020 17:07:19 +0100 Subject: [PATCH 03/11] Inline constants --- .../PdhHelper.cs | 4 +--- .../commands/utility/AddType.cs | 3 +-- .../host/msh/ConsoleHostUserInterfacePrompt.cs | 6 ++---- .../host/msh/PendingProgress.cs | 4 +--- .../engine/CommandCompletion/PseudoParameterBinder.cs | 3 +-- .../engine/MshCommandRuntime.cs | 3 +-- .../engine/SessionStateContainer.cs | 8 +++----- .../engine/runtime/ScriptBlockToPowerShell.cs | 3 +-- .../help/PSClassHelpProvider.cs | 9 ++------- 9 files changed, 13 insertions(+), 30 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 2e0e7cfe57f..54ab8842aba 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1061,8 +1061,6 @@ public uint GetValidPaths(string machineName, ref StringCollection instances, ref StringCollection validPaths) { - const uint res = 0; - PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); pathElts.MachineName = machineName; pathElts.ObjectName = objectName; @@ -1095,7 +1093,7 @@ public uint GetValidPaths(string machineName, } } - return res; + return 0; } public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 3c2c4e055db..3e1cf42cf85 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -903,12 +903,11 @@ private CommandLineArguments ParseCompilerOption(IEnumerable args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; - const string additionalReferenceDirectories = null; switch (Language) { case Language.CSharp: - return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); + return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory); default: throw PSTraceSource.NewNotSupportedException(); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 3171d71533c..73ec82e1d22 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -148,8 +148,6 @@ public override string fieldPrompt = null; fieldPrompt = desc.Name; - const bool fieldEchoOnPrompt = true; - // FieldDescription.ParameterAssemblyFullName never returns null. But this is // defense in depth. if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) @@ -211,7 +209,7 @@ public override bool inputListEnd = false; object convertedObj = null; string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, - desc, fieldEchoOnPrompt, true, out inputListEnd, out cancelInput, out convertedObj); + desc, fieldEchoOnPrompt: true, true, out inputListEnd, out cancelInput, out convertedObj); if (cancelInput || inputListEnd) { @@ -247,7 +245,7 @@ public override bool dummy = false; PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc, - fieldEchoOnPrompt, false, out dummy, out cancelInput, out convertedObj); + fieldEchoOnPrompt: true, false, out dummy, out cancelInput, out convertedObj); if (!cancelInput) { inputPSObject = PSObject.AsPSObject(convertedObj); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index c1ffc24bc96..1d40b2095f5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -836,11 +836,9 @@ internal override { nodesCompressed = 0; - const int age = 0; - while (true) { - ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, age, priorStyle); + ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, oldestSoFar: 0, priorStyle); if (node == null) { // We've compressed every node of the prior style already. diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 5b002d0b397..2479ebe8be5 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -261,8 +261,7 @@ public static class StaticParameterBinder /// The StaticBindingResult that represents the binding. public static StaticBindingResult BindCommand(CommandAst commandAst) { - const bool resolve = true; - return BindCommand(commandAst, resolve); + return BindCommand(commandAst, resolve: true); } /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index dd6ea513361..cf237440d15 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1734,8 +1734,7 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - const bool hasSecurityImpact = false; - return DoShouldContinue(query, caption, hasSecurityImpact, false, ref yesToAll, ref noToAll); + return DoShouldContinue(query, caption, hasSecurityImpact: false, false, ref yesToAll, ref noToAll); } /// diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 2093dce2472..626077082a5 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4796,9 +4796,8 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (languageMode.HasValue && (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage)) { - const string psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName; ps.Runspace = session.Runspace; - ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName); + ps.AddCommand("Get-Command").AddArgument(CopyFileRemoteUtils.PSCopyRemoteUtilsName); var result = ps.Invoke(); if (result.Count == 0) @@ -4822,12 +4821,11 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses ps.Commands.Clear(); ps.Streams.ClearStreams(); - ps.AddCommand(psRemoteUtilsName); + ps.AddCommand(CopyFileRemoteUtils.PSCopyRemoteUtilsName); } else { - const string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; - ps.AddScript(remoteScript); + ps.AddScript(CopyFileRemoteUtils.PSValidatePathDefinition); } ps.AddParameter("pathToValidate", path); diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index b53404463f8..7a60f07fe37 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -547,7 +547,6 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported"); Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type"); - const PipelineResultTypes toType = PipelineResultTypes.Output; PipelineResultTypes fromType; switch (commandAst.Redirections[0].FromStream) { @@ -581,7 +580,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) break; } - command.MergeMyResults(fromType, toType); + command.MergeMyResults(fromType, toResult: PipelineResultTypes.Output); } _powershell.AddCommand(command); diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index 7963657d000..e4c74c6398a 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -80,11 +80,9 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool else patternList.Add(target); - const bool useWildCards = true; - foreach (string pattern in patternList) { - PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards: true, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { @@ -108,10 +106,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) yield return null; } - string target = helpRequest.Target; - const bool useWildCards = false; - - PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(helpRequest.Target, useWildCards: false, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { From dde67bec5fd2b42f5d9a682d4511fff808fc1c49 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sun, 19 Jul 2020 20:25:44 +0100 Subject: [PATCH 04/11] Inline constants and refactor --- .../CommonUtils.cs | 16 +++--- .../remoting/commands/PushRunspaceCommand.cs | 49 ++++++++----------- .../remoting/common/RemoteSessionNamedPipe.cs | 17 +++---- .../remoting/common/RunspaceConnectionInfo.cs | 20 +++----- .../common/WireDataFormat/EncodeAndDecode.cs | 21 ++++---- .../help/UpdatableHelpCommandBase.cs | 6 +-- .../help/UpdatableHelpSystem.cs | 5 +- .../namespaces/RegistryProvider.cs | 25 +++++----- 8 files changed, 71 insertions(+), 88 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index 0b13d81d98f..0a016983443 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -57,7 +57,6 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou try { - const uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; uint LANGID = (uint)GetUserDefaultLangID(); uint langError = (uint)Marshal.GetLastWin32Error(); if (langError != 0) @@ -66,13 +65,14 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou } StringBuilder outStringBuilder = new StringBuilder(1024); - uint nChars = FormatMessage(dwFormatFlags, - moduleHandle, - lastError, - LANGID, - outStringBuilder, - (uint)outStringBuilder.Capacity, - IntPtr.Zero); + uint nChars = FormatMessage( + dwFlags: FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE, + lpSource: moduleHandle, + dwMessageId: lastError, + dwLanguageId: LANGID, + lpBuffer: outStringBuilder, + nSize: (uint)outStringBuilder.Capacity, + Arguments: IntPtr.Zero); if (nChars == 0) { diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index ba3a967f779..51bcb384705 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -794,15 +794,13 @@ private RemoteRunspace GetRunspaceMatchingCondition( /// private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { - Predicate condition = delegate (PSSession info) - { - return info.InstanceId == remoteRunspaceId; - }; - const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId); + return GetRunspaceMatchingCondition( + condition: (PSSession info) => info.InstanceId == remoteRunspaceId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + errorArgument: remoteRunspaceId); } /// @@ -810,15 +808,13 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) /// private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { - Predicate condition = delegate (PSSession info) - { - return info.Id == sessionId; - }; - const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; - const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId); + return GetRunspaceMatchingCondition( + condition: (PSSession info) => info.Id == sessionId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + errorArgument: sessionId); } /// @@ -826,16 +822,13 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) /// private RemoteRunspace GetRunspaceMatchingName(string name) { - Predicate condition = delegate (PSSession info) - { - // doing case-insensitive match for session name - return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); - }; - const PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; - const PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name); + return GetRunspaceMatchingCondition( + condition: (PSSession info) => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + errorArgument: name); } private Job FindJobForRunspace(Guid id) diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 7add4e1688b..6b2a5f67f4a 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -1302,9 +1302,6 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { - // Create pipe flags. - const uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly // attempt connection to pipe server until timeout expires. @@ -1317,13 +1314,13 @@ protected override NamedPipeClientStream DoConnect(int timeout) { // Get handle to pipe. pipeHandle = NamedPipeNative.CreateFile( - _pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - IntPtr.Zero, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: _pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + SecurityAttributes: IntPtr.Zero, + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (pipeHandle.IsInvalid) diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index d74986b674f..f8ebb19e1a0 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2626,21 +2626,15 @@ private static Process CreateProcessWithRedirectedStd( private static SafePipeHandle GetNamedPipeHandle(string pipeName) { - // Create pipe flags for asynchronous pipes. - const uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - - // We want an inheritable handle. - PlatformInvokes.SECURITY_ATTRIBUTES securityAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES(); - // Get handle to pipe. var fileHandle = PlatformInvokes.CreateFileW( - pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - securityAttributes, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle. + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode. + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index 83f69b6f951..e8834d2342e 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1196,10 +1196,10 @@ internal static RemoteDataObject GenerateRunspacePoolStateInfo( // Add Reason property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, a new ErrorRecord is - // created using this errorId - const string errorId = "RemoteRunspaceStateInfoReason"; - PSNoteProperty exceptionProperty = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemoteRunspaceStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1515,12 +1515,10 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn // Add exception property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, - // a new ErrorRecord is created using this errorId - const string errorId = "RemotePSInvocationStateInfoReason"; - PSNoteProperty exceptionProperty = - GetExceptionProperty(stateInfo.Reason, errorId, - ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemotePSInvocationStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1563,6 +1561,9 @@ internal static ErrorRecord GetErrorRecordFromException(Exception exception) /// /// Gets a Note Property for the exception. /// + /// + /// If is of not type IContainsErrorRecord, a new ErrorRecord is created. + /// /// /// ErrorId to use if exception is not of type IContainsErrorRecord. /// ErrorCategory to use if exception is not of type IContainsErrorRecord. diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 2aeed4294de..39d66f9ca18 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -299,9 +299,9 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf } } - // Match wildcards - const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new string[1] { moduleNamePattern }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); foreach (KeyValuePair name in s_metadataCache) { diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 99c22d78197..6fe42c8512c 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -586,8 +586,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new string[1] { currentCulture }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); for (int i = 0; i < updatableHelpItem.Length; i++) { diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 6ca03fe0410..ba95a45f20b 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1818,7 +1818,7 @@ public void GetProperty( // as the property name when adding the note, as // PSObject does not allow an empty propertyName - notePropertyName = GetLocalizedDefaultToken(); + notePropertyName = LocalizedDefaultToken; } propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); @@ -2023,7 +2023,7 @@ public void ClearProperty( string propertyNameToAdd = valueName; if (string.IsNullOrEmpty(valueName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); @@ -3055,7 +3055,7 @@ private void GetFilteredRegistryKeyProperties(string path, if (!string.IsNullOrEmpty(requestedValueName)) { - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } } @@ -3070,7 +3070,7 @@ private void GetFilteredRegistryKeyProperties(string path, // as the property name when adding the note, as // PSObject does not allow an empty propertyName - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } hadAMatch = true; @@ -3782,7 +3782,7 @@ private void WriteWrappedPropertyObject(object value, string propertyName, strin string propertyNameToAdd = propertyName; if (string.IsNullOrEmpty(propertyName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, value)); @@ -4028,7 +4028,7 @@ private void WriteRegistryItemObject( if (string.IsNullOrEmpty(valueNames[index])) { // The first unnamed value becomes the default value - valueNames[index] = GetLocalizedDefaultToken(); + valueNames[index] = LocalizedDefaultToken; break; } } @@ -4103,16 +4103,13 @@ private bool ParseKind(string type, out RegistryValueKind kind) /// Gets the default value name token from the resource. /// In English that token is "(default)" without the quotes. /// + /// + /// This should not be localized as it will break scripts. + /// /// /// A string containing the default value name. /// - private string GetLocalizedDefaultToken() - { - // This shouldn't be localized as it will break scripts - - const string defaultValueName = "(default)"; - return defaultValueName; - } + private string LocalizedDefaultToken => "(default)"; /// /// Converts an empty or null userEnteredPropertyName to the localized @@ -4135,7 +4132,7 @@ private string GetPropertyName(string userEnteredPropertyName) if (stringComparer.Compare( userEnteredPropertyName, - GetLocalizedDefaultToken(), + LocalizedDefaultToken, CompareOptions.IgnoreCase) == 0) { result = null; From b719e5be930bc22112d09a6dffe055932a831ab3 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sun, 19 Jul 2020 20:30:46 +0100 Subject: [PATCH 05/11] Extract constants --- .../help/UpdatableHelpSystem.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 6fe42c8512c..f6812a22a65 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -513,6 +513,9 @@ private string ResolveUri(string baseUri, bool verbose) private const string HelpInfoXmlNamespace = "http://schemas.microsoft.com/powershell/help/2010/05"; private const string HelpInfoXmlValidationFailure = "HelpInfoXmlValidationFailure"; + private const string MamlXmlNamespace = "http://schemas.microsoft.com/maml/2004/10"; + private const string CommandXmlNamespace = "http://schemas.microsoft.com/maml/dev/command/2004/10"; + private const string DscResourceXmlNamespace = "http://schemas.microsoft.com/maml/dev/dscResource/2004/10"; /// /// Creates a HelpInfo object. @@ -1306,8 +1309,6 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null"); - const string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; - foreach (XmlNode node in helpItemsNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element) @@ -1316,11 +1317,11 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de { if (node.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(MamlXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } else { @@ -1328,16 +1329,16 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de } } - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/command/2004/10", StringComparison.OrdinalIgnoreCase) && - !node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(CommandXmlNamespace, StringComparison.OrdinalIgnoreCase) && + !node.NamespaceURI.Equals(DscResourceXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } } - CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd, + CreateValidXmlDocument(node.OuterXml, MamlXmlNamespace, xsd, new ValidationEventHandler(HelpContentValidationHandler), false); } From f170b2add4453b0069126015ff335e2177846858 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 23 Jul 2020 12:32:22 +0100 Subject: [PATCH 06/11] Fix `CS0162: Unreachable code detected` --- .../common/DisplayDatabase/typeDataXmlLoader_Table.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index d5f549b6a72..acc60a3e3e5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -353,7 +353,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde using (this.StackFrame(rowEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 - const bool columnEntriesNodeFound = false; // cardinality 1 + bool columnEntriesNodeFound = false; // cardinality 1 bool multiLineFound = false; // cardinality 0..1 TableRowDefinition trd = new TableRowDefinition(); From d71f523d3c39bb2c7e9e48ac46af282780ef09b6 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 23 Jul 2020 12:34:34 +0100 Subject: [PATCH 07/11] Fix Codacy issues --- .../engine/remoting/commands/PushRunspaceCommand.cs | 6 +++--- .../help/UpdatableHelpCommandBase.cs | 2 +- .../help/UpdatableHelpSystem.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 51bcb384705..64e7cd6a245 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -795,7 +795,7 @@ private RemoteRunspace GetRunspaceMatchingCondition( private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { return GetRunspaceMatchingCondition( - condition: (PSSession info) => info.InstanceId == remoteRunspaceId, + condition: info => info.InstanceId == remoteRunspaceId, tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, @@ -809,7 +809,7 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { return GetRunspaceMatchingCondition( - condition: (PSSession info) => info.Id == sessionId, + condition: info => info.Id == sessionId, tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, @@ -823,7 +823,7 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) private RemoteRunspace GetRunspaceMatchingName(string name) { return GetRunspaceMatchingCondition( - condition: (PSSession info) => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), + condition: info => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName, tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 39d66f9ca18..4d052f29e96 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -300,7 +300,7 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf } IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( - globPatterns: new string[1] { moduleNamePattern }, + globPatterns: new[] { moduleNamePattern }, options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); foreach (KeyValuePair name in s_metadataCache) diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index f6812a22a65..ade5ffaa64c 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -590,7 +590,7 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( - globPatterns: new string[1] { currentCulture }, + globPatterns: new[] { currentCulture }, options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); for (int i = 0; i < updatableHelpItem.Length; i++) From ab2720523b1d0d8ef88ba33f1df457dc778ac3d3 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 23 Jul 2020 15:51:42 +0100 Subject: [PATCH 08/11] Final cleanup --- .../engine/Modules/ModuleIntrinsics.cs | 2 +- .../engine/NativeCommandParameterBinder.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index db1191ed1d7..faad529ea93 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -703,7 +703,7 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) } #if UNIX - StringComparison strcmp = StringComparison.Ordinal; + const StringComparison strcmp = StringComparison.Ordinal; #else const StringComparison strcmp = StringComparison.OrdinalIgnoreCase; #endif diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index e77ac6d5192..0091596a443 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -260,7 +260,7 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array /// Bare, SingleQuoted, or DoubleQuoted. private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) { - bool argExpanded = false; + var argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against From e3c79a21d9b4124bd3587f58f2227a5533d15985 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sat, 25 Jul 2020 18:15:54 +0100 Subject: [PATCH 09/11] Label bools and indent all arguments address @rjmholt feedback --- .../msh/ConsoleHostUserInterfacePrompt.cs | 36 ++++++++++++++----- .../engine/MshCommandRuntime.cs | 8 ++++- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 73ec82e1d22..1d283469b9c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -206,12 +206,22 @@ public override { fieldPromptList.Append( string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); - bool inputListEnd = false; + bool endListInput = false; object convertedObj = null; - string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, - desc, fieldEchoOnPrompt: true, true, out inputListEnd, out cancelInput, out convertedObj); - - if (cancelInput || inputListEnd) + string inputString = PromptForSingleItem( + elementType, + fieldPromptList.ToString(), + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: true, + out endListInput, + out cancelInput, + out convertedObj); + + if (cancelInput || endListInput) { break; } @@ -242,10 +252,20 @@ public override fieldPrompt); // field is not a list object convertedObj = null; - bool dummy = false; - PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc, - fieldEchoOnPrompt: true, false, out dummy, out cancelInput, out convertedObj); + PromptForSingleItem( + fieldType, + printFieldPrompt, + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: false, + endListInput: out _, + out cancelInput, + out convertedObj); + if (!cancelInput) { inputPSObject = PSObject.AsPSObject(convertedObj); diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index cf237440d15..8ef5b942656 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1734,7 +1734,13 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - return DoShouldContinue(query, caption, hasSecurityImpact: false, false, ref yesToAll, ref noToAll); + return DoShouldContinue( + query, + caption, + hasSecurityImpact: false, + supportsToAllOptions: false, + ref yesToAll, + ref noToAll); } /// From b72e3bdee0fd86499c13ec80c27f1d91105dd232 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sat, 25 Jul 2020 18:17:12 +0100 Subject: [PATCH 10/11] Fixes inside `#if UNIX` --- .../commands/management/ComputerUnix.cs | 4 +--- .../commands/utility/UnblockFile.cs | 2 +- src/powershell/Program.cs | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index 023fc1d0501..c57e35f1733 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -137,14 +137,12 @@ protected override void StopProcessing() /// Run a command. /// protected void RunCommand(String command, String args) { - String cmd = ""; - _process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/sbin/shutdown", - Arguments = cmd, + Arguments = "", RedirectStandardOutput = false, UseShellExecute = false, CreateNoWindow = true, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index fad330212ed..c521b670df7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -198,7 +198,7 @@ private bool IsValidFileForUnblocking(string resolvedpath) #if UNIX private bool IsBlocked(string path) { - uint valueSize = 1024; + const uint valueSize = 1024; IntPtr value = Marshal.AllocHGlobal((int)valueSize); try { diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index e4d3b51c5d6..e6ccd4768cc 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -359,7 +359,7 @@ private static void CreatePwshInvocation( (string path, int quotedLength) invocationInfo) { // "exec " - string prefix = "exec "; + const string prefix = "exec "; prefix.AsSpan().CopyTo(strBuf); // The quoted path to pwsh, like "'/opt/microsoft/powershell/7/pwsh'" @@ -369,7 +369,7 @@ private static void CreatePwshInvocation( i += invocationInfo.quotedLength; // ' "$@"' the argument vector splat to pass pwsh arguments through - string suffix = " \"$@\""; + const string suffix = " \"$@\""; Span bufSuffix = strBuf.Slice(i); suffix.AsSpan().CopyTo(bufSuffix); } From 1e4677f2c75fdf224de6e5b9243450210b99ba43 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Sat, 25 Jul 2020 18:35:29 +0100 Subject: [PATCH 11/11] Discard unused var Fix Codacy issue --- .../host/msh/ConsoleHostUserInterfacePrompt.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 1d283469b9c..51445db0915 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -208,7 +208,7 @@ public override string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); bool endListInput = false; object convertedObj = null; - string inputString = PromptForSingleItem( + _ = PromptForSingleItem( elementType, fieldPromptList.ToString(), fieldPrompt, @@ -253,7 +253,7 @@ public override // field is not a list object convertedObj = null; - PromptForSingleItem( + _ = PromptForSingleItem( fieldType, printFieldPrompt, fieldPrompt,