diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index caac54d654f..c90e7800c2d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -357,7 +357,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 cffc347c38f..fb788b4d26c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -55,7 +55,6 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou try { - 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) @@ -64,13 +63,14 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou } StringBuilder outStringBuilder = new(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/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index bfc56e8b172..97eff22db0d 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1057,8 +1057,6 @@ public uint GetValidPaths(string machineName, ref StringCollection instances, ref StringCollection validPaths) { - uint res = PdhResults.PDH_CSTATUS_VALID_DATA; - PDH_COUNTER_PATH_ELEMENTS pathElts = new(); pathElts.MachineName = machineName; pathElts.ObjectName = objectName; @@ -1091,7 +1089,7 @@ public uint GetValidPaths(string machineName, } } - return res; + return PdhResults.PDH_CSTATUS_VALID_DATA; } public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) 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.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index 425acabe7f4..fb01823790f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -154,14 +154,12 @@ protected override void StopProcessing() /// Run a command. /// protected void RunCommand(String command, String args) { - String cmd = string.Empty; - _process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/sbin/shutdown", - Arguments = cmd, + Arguments = string.Empty, RedirectStandardOutput = false, UseShellExecute = false, CreateNoWindow = true, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 242e5b1c5c5..a2ffec58392 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -914,12 +914,11 @@ private CommandLineArguments ParseCompilerOption(IEnumerable args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; - 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.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 0c2481b8eee..0523e2e0c35 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 static 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 3628a36fdff..4c7fd83ce73 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 @@ -486,7 +486,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 @@ -508,7 +508,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 e218ac9d6dd..2b1aab06ae9 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 @@ -188,9 +188,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) @@ -230,7 +230,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 d14ffbfc2e8..b32ed855e60 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -559,7 +559,7 @@ internal ErrorDetails GetErrorDetails(string errorId, params object[] args) private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() { - string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; + const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; ErrorDetails details = this.GetErrorDetails(errorId); @@ -580,7 +580,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorMalformedDataFromRemoteCommand"; + const string errorId = "ErrorMalformedDataFromRemoteCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -601,7 +601,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames throw PSTraceSource.NewArgumentNullException(nameof(commandNames)); } - string errorId = "ErrorCommandSkippedBecauseOfShadowing"; + const string errorId = "ErrorCommandSkippedBecauseOfShadowing"; ErrorDetails details = this.GetErrorDetails(errorId, commandNames); @@ -622,7 +622,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedNonRequestedCommand"; + const string errorId = "ErrorSkippedNonRequestedCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -643,7 +643,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } - string errorId = "ErrorSkippedNonRequestedTypeDefinition"; + const string errorId = "ErrorSkippedNonRequestedTypeDefinition"; ErrorDetails details = this.GetErrorDetails(errorId, typeName); @@ -664,7 +664,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedUnsafeCommandName"; + const string errorId = "ErrorSkippedUnsafeCommandName"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -771,7 +771,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) throw PSTraceSource.NewArgumentNullException(nameof(aliasName)); } - string errorId = "ErrorCouldntResolveAlias"; + const string errorId = "ErrorCouldntResolveAlias"; ErrorDetails details = this.GetErrorDetails(errorId, aliasName); @@ -792,7 +792,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/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index ba5a8f8a532..78160785d98 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -199,7 +199,7 @@ private bool IsValidFileForUnblocking(string resolvedpath) #if UNIX private static bool IsBlocked(string path) { - uint valueSize = 1024; + const uint valueSize = 1024; IntPtr value = Marshal.AllocHGlobal((int)valueSize); try { 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 2005d587b97..f540fa67636 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 @@ -1831,7 +1831,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..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); - var STARTF_USESHOWWINDOW = 0x00000001; - var 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/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 448bcb5f586..c2458fabb5e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2477,7 +2477,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 55b3a04c3e6..8b0ee08f5aa 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1779,7 +1779,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) @@ -2029,7 +2029,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 89b9303b856..6d7caefec36 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -147,8 +147,6 @@ public override string fieldPrompt = null; fieldPrompt = desc.Name; - bool fieldEchoOnPrompt = true; - // FieldDescription.ParameterAssemblyFullName never returns null. But this is // defense in depth. if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) @@ -207,12 +205,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, out inputListEnd, out cancelInput, out convertedObj); - - if (cancelInput || inputListEnd) + _ = PromptForSingleItem( + elementType, + fieldPromptList.ToString(), + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: true, + out endListInput, + out cancelInput, + out convertedObj); + + if (cancelInput || endListInput) { break; } @@ -243,10 +251,20 @@ public override fieldPrompt); // field is not a list object convertedObj = null; - bool dummy = false; - PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc, - fieldEchoOnPrompt, 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/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index a3711200971..da9d5689105 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -297,7 +297,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 1588efe6b0e..89901b18126 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -825,11 +825,9 @@ internal override { nodesCompressed = 0; - 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/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 2286b6465a5..720af780642 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 0bb8c049d03..fdbac1ca8d2 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -635,7 +635,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); } } @@ -721,7 +721,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); } @@ -746,7 +746,7 @@ protected override void RemoveItem( if (fUserContext) { string message = CertificateProviderStrings.CannotDeleteUserStore; - string errorId = "CannotDeleteUserStore"; + const string errorId = "CannotDeleteUserStore"; ThrowInvalidOperation(errorId, message); } @@ -756,7 +756,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); } } @@ -827,7 +827,7 @@ protected override void MoveItem( if (isContainer) { string message = CertificateProviderStrings.CannotMoveContainer; - string errorId = "CannotMoveContainer"; + const string errorId = "CannotMoveContainer"; ThrowInvalidOperation(errorId, message); } @@ -844,7 +844,7 @@ protected override void MoveItem( else { string message = CertificateProviderStrings.InvalidDestStore; - string errorId = "InvalidDestStore"; + const string errorId = "InvalidDestStore"; ThrowInvalidOperation(errorId, message); } } @@ -856,14 +856,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); } @@ -877,7 +877,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); } } @@ -961,7 +961,7 @@ protected override void NewItem( if (pathElements.Length != 2) { string message = CertificateProviderStrings.CannotCreateItem; - string errorId = "CannotCreateItem"; + const string errorId = "CannotCreateItem"; ThrowInvalidOperation(errorId, message); } @@ -971,11 +971,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; @@ -1415,7 +1415,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"); @@ -1773,7 +1773,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 | @@ -1794,7 +1794,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); } } @@ -2828,7 +2828,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 60d8795ac54..cd5e6d3fc4d 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -227,7 +227,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()) { @@ -508,7 +508,7 @@ private void EnableClientSideSettings() return; } - string newxmlcontent = @"true"; + const string newxmlcontent = @"true"; try { XmlDocument xmldoc = new XmlDocument(); @@ -626,7 +626,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()) { @@ -827,7 +827,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 98d9c2feb24..525717164a9 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 e3ff3608b9d..48ab1307681 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 9c0fbc90b66..742f9936ea8 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/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 7394589bb95..bfd3291dd46 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 c158583e25b..0737e43476e 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 e5d456eb854..c86fc34cfaf 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) { - bool resolve = true; - return BindCommand(commandAst, resolve); + return BindCommand(commandAst, resolve: true); } /// diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 18332cc37c6..5c166c69a63 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 578a832e34a..94fc57ea0d7 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 5d1451a3971..86ff0666e2c 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 5e6b44b9ada..c132db5dfba 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1141,7 +1141,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 71f86332861..cd354719660 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -703,9 +703,9 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) } #if UNIX - StringComparison strcmp = StringComparison.Ordinal; + const 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 b87a14c8f26..9ece4af620f 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 cc1b38d7d0d..92238db5e31 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1735,8 +1735,13 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - bool hasSecurityImpact = false; - return DoShouldContinue(query, caption, hasSecurityImpact, false, ref yesToAll, ref noToAll); + return DoShouldContinue( + query, + caption, + hasSecurityImpact: false, + supportsToAllOptions: false, + ref yesToAll, + ref noToAll); } /// diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index a2b6f3baffa..76bb2d54a6f 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4790,9 +4790,8 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (languageMode.HasValue && (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage)) { - var 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) @@ -4816,12 +4815,11 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses ps.Commands.Clear(); ps.Streams.ClearStreams(); - ps.AddCommand(psRemoteUtilsName); + ps.AddCommand(CopyFileRemoteUtils.PSCopyRemoteUtilsName); } else { - string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; - ps.AddScript(remoteScript); + ps.AddScript(CopyFileRemoteUtils.PSValidatePathDefinition); } ps.AddParameter("pathToValidate", path); diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 331629f086e..d015cd3e45f 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -4451,13 +4451,13 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> string computerName = _runspace.ConnectionInfo?.ComputerName; - 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 6b6a099e5c3..dcfe06245af 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -912,7 +912,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); @@ -928,7 +928,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 2543c5273d0..ce61c645233 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1217,7 +1217,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 ea90e87390b..1fa03edf25b 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 static 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 7dd4209a782..c9202190221 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 82459fdab92..b309fe142a7 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 02115bb2f47..f306246e289 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 656b439f8a0..cbc5f82742b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -791,12 +791,13 @@ private RemoteRunspace GetRunspaceMatchingCondition( /// private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { - Predicate condition = (PSSession info) => info.InstanceId == remoteRunspaceId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId); + return GetRunspaceMatchingCondition( + condition: info => info.InstanceId == remoteRunspaceId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + errorArgument: remoteRunspaceId); } /// @@ -804,12 +805,13 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) /// private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { - Predicate condition = (PSSession info) => info.Id == sessionId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId); + return GetRunspaceMatchingCondition( + condition: info => info.Id == sessionId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + errorArgument: sessionId); } /// @@ -817,16 +819,13 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) /// private RemoteRunspace GetRunspaceMatchingName(string name) { - Predicate condition = (PSSession info) => - { - // doing case-insensitive match for session name - return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); - }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name); + return GetRunspaceMatchingCondition( + condition: 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/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 2537abe6369..094dcedc6ad 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 07d17ae3e51..6f520e0ac26 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -1291,9 +1291,6 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { - // Create pipe flags. - 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. @@ -1306,13 +1303,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 e577ba67187..9debc89ce76 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2050,9 +2050,9 @@ internal int StartSSHProcess( { string filePath = string.Empty; #if UNIX - string sshCommand = "ssh"; + const string sshCommand = "ssh"; #else - string sshCommand = "ssh.exe"; + const string sshCommand = "ssh.exe"; #endif var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) @@ -2625,21 +2625,15 @@ private static Process CreateProcessWithRedirectedStd( private static SafePipeHandle GetNamedPipeHandle(string pipeName) { - // Create pipe flags for asynchronous pipes. - 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 febb87721cc..03a3cd51a87 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 - 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 - 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/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index d0439613408..abcb32966f3 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 d354574c37b..1bf8afd3dd1 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/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index d9b4d734900..d98239c3c33 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 0c6691532b8..b70f0cb4b4d 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -2066,7 +2066,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); @@ -2712,7 +2712,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 c6091aceee6..5fdc13e0efc 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 4f649e19fc1..f5d2f51f698 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"); - 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/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index e6eafa8704f..5feb3c00189 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1250,7 +1250,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 e67caa40db8..edf8d9e4355 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -516,7 +516,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 beda31bfd8e..21ac7b9e79d 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..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); - 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; - 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)) { diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 9697ffb2f25..d9453b58c2e 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 - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + 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 add71bd55b5..f7a476d5d07 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. @@ -586,8 +589,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new[] { currentCulture }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); for (int i = 0; i < updatableHelpItem.Length; i++) { @@ -1305,8 +1309,6 @@ 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"; - foreach (XmlNode node in helpItemsNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element) @@ -1315,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 { @@ -1327,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); } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 8d77bc000d1..1b7822d634c 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -4195,7 +4195,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 "; @@ -4373,7 +4373,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; @@ -4506,7 +4506,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 "; @@ -4624,7 +4624,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; @@ -6771,7 +6771,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; @@ -8287,10 +8287,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)) @@ -8326,10 +8326,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)) { @@ -8629,7 +8629,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 149a3711f7d..29e37a163e4 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1819,7 +1819,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))); @@ -2024,7 +2024,7 @@ public void ClearProperty( string propertyNameToAdd = valueName; if (string.IsNullOrEmpty(valueName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); @@ -3056,7 +3056,7 @@ private void GetFilteredRegistryKeyProperties(string path, if (!string.IsNullOrEmpty(requestedValueName)) { - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } } @@ -3071,7 +3071,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; @@ -3783,7 +3783,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)); @@ -4033,7 +4033,7 @@ private void WriteRegistryItemObject( if (string.IsNullOrEmpty(valueNames[index])) { // The first unnamed value becomes the default value - valueNames[index] = GetLocalizedDefaultToken(); + valueNames[index] = LocalizedDefaultToken; break; } } @@ -4108,16 +4108,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 - - string defaultValueName = "(default)"; - return defaultValueName; - } + private string LocalizedDefaultToken => "(default)"; /// /// Converts an empty or null userEnteredPropertyName to the localized @@ -4140,7 +4137,7 @@ private string GetPropertyName(string userEnteredPropertyName) if (stringComparer.Compare( userEnteredPropertyName, - GetLocalizedDefaultToken(), + LocalizedDefaultToken, CompareOptions.IgnoreCase) == 0) { result = null; diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index f984976b33d..0c1c76b63e4 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -409,8 +409,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 226082be67e..49181e34584 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -160,7 +160,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/src/powershell/Program.cs b/src/powershell/Program.cs index edac5b24f04..c885fa7fd2e 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -370,7 +370,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'" @@ -380,7 +380,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); } 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 b30c3ad18f8..ea45ce533d6 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 {