From 21809a0f1c59be66c182cfb7d58c6be2c38d80ca Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 22:35:43 +0100 Subject: [PATCH 01/12] Fix CA1822 for internal visibility --- .globalconfig | 2 +- .../CimSessionOperations.cs | 4 +- .../GetCounterCommand.cs | 2 +- .../PdhHelper.cs | 4 +- .../commands/management/Service.cs | 4 +- .../utility/ImplicitRemotingCommands.cs | 24 ++--- .../commands/utility/Join-String.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 8 +- .../host/msh/ConsoleHost.cs | 2 +- .../host/msh/ConsoleHostUserInterface.cs | 2 +- .../security/CertificateProvider.cs | 10 +- .../ConfigProvider.cs | 96 +++++++++---------- src/Microsoft.WSMan.Management/CredSSP.cs | 44 ++++----- .../InvokeWSManAction.cs | 2 +- .../NewWSManSession.cs | 4 +- src/Microsoft.WSMan.Management/PingWSMan.cs | 2 +- .../Set-QuickConfig.cs | 4 +- .../WSManConnections.cs | 12 +-- .../WSManInstance.cs | 16 ++-- src/Microsoft.WSMan.Management/WsManHelper.cs | 16 ++-- .../CoreCLR/CorePsStub.cs | 2 +- .../common/BaseFormattingCommand.cs | 2 +- .../DisplayDatabase/typeDataXmlLoader.cs | 4 +- .../common/FormatViewGenerator.cs | 2 +- .../common/FormattingObjectsDeserializer.cs | 4 +- .../common/Utilities/MshObjectUtil.cs | 2 +- .../engine/COM/ComProperty.cs | 2 +- .../engine/ComInterop/ComTypeLibDesc.cs | 2 +- .../CommandCompletion/CompletionCompleters.cs | 2 +- .../PseudoParameterBinder.cs | 2 +- .../engine/CommandMetadata.cs | 4 +- .../engine/CommandProcessor.cs | 2 +- .../engine/CommandProcessorBase.cs | 2 +- .../engine/CoreAdapter.cs | 6 +- .../engine/DataStoreAdapterProvider.cs | 2 +- .../engine/EventManager.cs | 2 +- .../engine/ExternalScriptInfo.cs | 4 +- .../engine/ManagementObjectAdapter.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 6 +- .../engine/Modules/ModuleIntrinsics.cs | 2 +- .../engine/MshCommandRuntime.cs | 2 +- .../engine/ProxyCommand.cs | 4 +- .../engine/SessionStateContainer.cs | 2 +- .../engine/SessionStateProviderAPIs.cs | 2 +- .../engine/Utils.cs | 2 +- .../engine/cmdlet.cs | 2 +- .../InternalHostRawUserInterface.cs | 3 +- .../hostifaces/InternalHostUserInterface.cs | 2 +- .../engine/parser/Compiler.cs | 6 +- .../engine/parser/Parser.cs | 2 +- .../engine/parser/TypeInferenceVisitor.cs | 8 +- .../engine/parser/tokenizer.cs | 2 +- .../engine/remoting/client/Job.cs | 2 +- .../remoting/commands/PSRemotingCmdlet.cs | 2 +- .../remoting/commands/newrunspacecommand.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 4 +- .../fanin/OutOfProcTransportManager.cs | 2 +- .../engine/remoting/fanin/WSManPlugin.cs | 2 +- .../engine/runtime/CompiledScriptBlock.cs | 2 +- .../help/UpdatableHelpCommandBase.cs | 6 +- .../help/UpdatableHelpSystem.cs | 4 +- .../help/UpdateHelpCommand.cs | 2 +- .../namespaces/FileSystemProvider.cs | 2 +- .../utils/tracing/PSEtwLog.cs | 30 +++--- .../utils/tracing/PSEtwLogProvider.cs | 8 +- test/xUnit/csharp/test_PSConfiguration.cs | 26 ++--- test/xUnit/csharp/test_Prediction.cs | 2 +- 67 files changed, 224 insertions(+), 225 deletions(-) diff --git a/.globalconfig b/.globalconfig index d7fb942772c..67733422919 100644 --- a/.globalconfig +++ b/.globalconfig @@ -408,7 +408,7 @@ dotnet_diagnostic.CA1821.severity = warning # CA1822: Mark members as static # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822 dotnet_diagnostic.CA1822.severity = warning -dotnet_code_quality.CA1822.api_surface = private +dotnet_code_quality.CA1822.api_surface = private, internal # CA1823: Avoid unused private fields # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1823 diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index c22db2087e4..41e137387f3 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -389,7 +389,7 @@ internal PSObject AddObjectToCache( /// /// /// - internal string GetRemoveSessionObjectTarget(PSObject psObject) + internal static string GetRemoveSessionObjectTarget(PSObject psObject) { string message = string.Empty; if (psObject.BaseObject is CimSession) @@ -1192,7 +1192,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) { foreach (PSObject psobject in sessionToRemove) { - if (cmdlet.ShouldProcess(this.sessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName)) + if (cmdlet.ShouldProcess(CimSessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName)) { this.sessionState.RemoveOneSessionObjectFromCache(psobject); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index f04c8ceff0f..568316c4f0a 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -377,7 +377,7 @@ private void ProcessListSetPerMachine(string machine) categoryType = PerformanceCounterCategoryType.SingleInstance; } - string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet); + string setHelp = PdhHelper.GetCounterSetHelp(machine, counterSet); CounterSet setObj = new(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping); WriteObject(setObj); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 97eff22db0d..dfddaa6b0a4 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1016,7 +1016,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa return res; } - public uint LookupPerfNameByIndex(string machineName, uint index, out string locName) + public static uint LookupPerfNameByIndex(string machineName, uint index, out string locName) { // // NOTE: to make PdhLookupPerfNameByIndex() work, @@ -1133,7 +1133,7 @@ public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) return bAtLeastOneAdded ? PdhResults.PDH_CSTATUS_VALID_DATA : res; } - public string GetCounterSetHelp(string szMachineName, string szObjectName) + public static string GetCounterSetHelp(string szMachineName, string szObjectName) { // API not available to retrieve return string.Empty; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index a089f204654..9d3a434edb9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -304,7 +304,7 @@ public ServiceController[] InputObject private ServiceController[] _allServices; - internal ServiceController GetOneService(string nameOfService) + internal static ServiceController GetOneService(string nameOfService) { Dbg.Assert(!WildcardPattern.ContainsWildcardCharacters(nameOfService), "Caller should verify that nameOfService doesn't contain wildcard characters"); @@ -1085,7 +1085,7 @@ private static bool HaveAllDependentServicesStopped(ServiceController[] dependen /// This removes all services that are not stopped from a list of services. /// /// A list of services. - internal void RemoveNotStoppedServices(List services) + internal static void RemoveNotStoppedServices(List services) { // You shall not modify a collection during enumeration. services.RemoveAll(service => diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index d772258227b..cad363346f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -543,7 +543,7 @@ public string[] FormatTypeName #region Localized errors and messages - internal ErrorDetails GetErrorDetails(string errorId, params object[] args) + internal static ErrorDetails GetErrorDetails(string errorId, params object[] args) { if (string.IsNullOrEmpty(errorId)) { @@ -561,7 +561,7 @@ private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() { const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; - ErrorDetails details = this.GetErrorDetails(errorId); + ErrorDetails details = GetErrorDetails(errorId); ErrorRecord errorRecord = new( new ArgumentException(details.Message), @@ -582,7 +582,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) const string errorId = "ErrorMalformedDataFromRemoteCommand"; - ErrorDetails details = this.GetErrorDetails(errorId, commandName); + ErrorDetails details = GetErrorDetails(errorId, commandName); ErrorRecord errorRecord = new( new ArgumentException(details.Message), @@ -603,7 +603,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames const string errorId = "ErrorCommandSkippedBecauseOfShadowing"; - ErrorDetails details = this.GetErrorDetails(errorId, commandNames); + ErrorDetails details = GetErrorDetails(errorId, commandNames); ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), @@ -624,7 +624,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) const string errorId = "ErrorSkippedNonRequestedCommand"; - ErrorDetails details = this.GetErrorDetails(errorId, commandName); + ErrorDetails details = GetErrorDetails(errorId, commandName); ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), @@ -645,7 +645,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) const string errorId = "ErrorSkippedNonRequestedTypeDefinition"; - ErrorDetails details = this.GetErrorDetails(errorId, typeName); + ErrorDetails details = GetErrorDetails(errorId, typeName); ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), @@ -666,7 +666,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) const string errorId = "ErrorSkippedUnsafeCommandName"; - ErrorDetails details = this.GetErrorDetails(errorId, commandName); + ErrorDetails details = GetErrorDetails(errorId, commandName); ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), @@ -698,7 +698,7 @@ private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, stri string errorId = "ErrorSkippedUnsafe" + nameType + "Name"; - ErrorDetails details = this.GetErrorDetails(errorId, commandName, name); + ErrorDetails details = GetErrorDetails(errorId, commandName, name); ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), @@ -735,7 +735,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { errorId = "ErrorRequiredRemoteCommandNotFound"; - errorDetails = this.GetErrorDetails(errorId, this.MyInvocation.MyCommand.Name); + errorDetails = GetErrorDetails(errorId, this.MyInvocation.MyCommand.Name); errorRecord = new ErrorRecord( new RuntimeException(errorDetails.Message, runtimeException), @@ -752,7 +752,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // output a generic error message if exception is not recognized // errorId = "ErrorFromRemoteCommand"; - errorDetails = this.GetErrorDetails(errorId, commandName, runtimeException.Message); + errorDetails = GetErrorDetails(errorId, commandName, runtimeException.Message); errorRecord = new ErrorRecord( new RuntimeException(errorDetails.Message, runtimeException), @@ -773,7 +773,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) const string errorId = "ErrorCouldntResolveAlias"; - ErrorDetails details = this.GetErrorDetails(errorId, aliasName); + ErrorDetails details = GetErrorDetails(errorId, aliasName); ErrorRecord errorRecord = new( new ArgumentException(details.Message), @@ -794,7 +794,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) const string errorId = "ErrorNoResultsFromRemoteEnd"; - ErrorDetails details = this.GetErrorDetails(errorId, commandName); + ErrorDetails details = GetErrorDetails(errorId, commandName); ErrorRecord errorRecord = new( new ArgumentException(details.Message), diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index 0aebabe94c7..68e0408f8ec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -223,7 +223,7 @@ void AddMatching(string completionText, string listText, string toolTip) return res; } - public string NewLineText + public static string NewLineText { get { 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 604582661a0..62e28e54193 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 @@ -1656,7 +1656,7 @@ protected override void StopProcessing() /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, byte[] content) + internal static long SetRequestContent(HttpRequestMessage request, byte[] content) { if (request == null) throw new ArgumentNullException(nameof(request)); @@ -1728,7 +1728,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) return byteArrayContent.Headers.ContentLength.Value; } - internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) + internal static long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { if (request == null) throw new ArgumentNullException(nameof(request)); @@ -1765,7 +1765,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) + internal static long SetRequestContent(HttpRequestMessage request, Stream contentStream) { if (request == null) throw new ArgumentNullException(nameof(request)); @@ -1788,7 +1788,7 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) + internal static long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { if (request == null) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 167186ae0c6..8b552d6595e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2446,7 +2446,7 @@ internal void Run(bool inputLoopIsNested) if (ui.SupportsVirtualTerminal) { // need to re-enable VT mode if it was previously enabled as native commands may have turned it off - ui.TryTurnOnVtMode(); + ConsoleHostUserInterface.TryTurnOnVtMode(); } #endif diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 822daa12828..f026b6ed748 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -94,7 +94,7 @@ internal ConsoleHostUserInterface(ConsoleHost parent) } } - internal bool TryTurnOnVtMode() + internal static bool TryTurnOnVtMode() { #if UNIX return true; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 1292ecb9b55..76f4c9570b2 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -462,7 +462,7 @@ public IntPtr GetCertByName(string Name) return certContext; } - public void FreeCert(IntPtr certContext) + public static void FreeCert(IntPtr certContext) { Security.NativeMethods.CertFreeCertificateContext(certContext); } @@ -1081,7 +1081,7 @@ protected override bool HasChildItems(string path) IntPtr certContext = store.GetFirstCert(); if (certContext != IntPtr.Zero) { - store.FreeCert(certContext); + X509NativeStore.FreeCert(certContext); result = true; } } @@ -2112,7 +2112,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) item = new X509Certificate2(certContext); } - store.FreeCert(certContext); + X509NativeStore.FreeCert(certContext); break; @@ -2914,7 +2914,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) CultureInfo currentUICulture = CultureInfo.CurrentUICulture; string fullHelpPath = Path.Combine( - this.ProviderInfo.ApplicationBase, + ProviderInfo.ApplicationBase, currentUICulture.ToString(), this.ProviderInfo.HelpFile); XmlReaderSettings settings = new(); @@ -3219,7 +3219,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin if (certContext != IntPtr.Zero) { certFromStore = new X509Certificate2(certContext); - store.FreeCert(certContext); + X509NativeStore.FreeCert(certContext); } } diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index de99812b01d..9c7edc3a5ac 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -195,7 +195,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) if (!string.IsNullOrEmpty(drive.Root)) { - AssertError(helper.GetResourceMsgFromResourcetext("NewDriveRootDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("NewDriveRootDoesNotExist"), false); return null; } @@ -210,7 +210,7 @@ protected override Collection InitializeDefaultDrives() { Collection drives = new Collection(); drives.Add(new PSDriveInfo(WSManStringLiterals.rootpath, ProviderInfo, string.Empty, - helper.GetResourceMsgFromResourcetext("ConfigStorage"), null)); + WSManHelper.GetResourceMsgFromResourcetext("ConfigStorage"), null)); return drives; } @@ -875,14 +875,14 @@ protected override void SetItem(string path, object value) { if (value == null) { - throw new ArgumentException(helper.GetResourceMsgFromResourcetext("value")); + throw new ArgumentException(WSManHelper.GetResourceMsgFromResourcetext("value")); } string ChildName = string.Empty; if (path.Length == 0 && string.IsNullOrEmpty(ChildName)) { - AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); return; } @@ -898,7 +898,7 @@ protected override void SetItem(string path, object value) if (ChildName.Equals(path, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); return; } @@ -920,12 +920,12 @@ protected override void SetItem(string path, object value) // if he intends to disable RunAs on the Plugin. if (string.Equals(ChildName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("ClearItemOnRunAsPassword"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ClearItemOnRunAsPassword"), false); return; } } - string whatIfMessage = string.Format(CultureInfo.CurrentUICulture, helper.GetResourceMsgFromResourcetext("SetItemWhatIfAndConfirmText"), path, value); + string whatIfMessage = string.Format(CultureInfo.CurrentUICulture, WSManHelper.GetResourceMsgFromResourcetext("SetItemWhatIfAndConfirmText"), path, value); if (!ShouldProcess(whatIfMessage, string.Empty, string.Empty)) { return; @@ -977,7 +977,7 @@ protected override void SetItem(string path, object value) { if (path.EndsWith(strPathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); } try @@ -990,7 +990,7 @@ protected override void SetItem(string path, object value) if (!this.clearItemIsCalled) { // Don't need an error if ClearItem is called. - AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); } return; @@ -1047,7 +1047,7 @@ protected override void SetItem(string path, object value) WSManStringLiterals.ConfigRunAsUserName)))) { // User Cannot set RunAsPassword if, RunAsUser is not present. - AssertError(helper.GetResourceMsgFromResourcetext("SetItemOnRunAsPasswordNoRunAsUser"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemOnRunAsPasswordNoRunAsUser"), false); } value = GetStringFromSecureString(value); @@ -1061,7 +1061,7 @@ protected override void SetItem(string path, object value) { if (path.EndsWith(strPathChk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); return; } @@ -1088,7 +1088,7 @@ protected override void SetItem(string path, object value) if (ChildName.Equals(WSManStringLiterals.ConfigResourceUriName, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("NoChangeValue"), false); return; } @@ -1112,7 +1112,7 @@ protected override void SetItem(string path, object value) } else { - AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("NoChangeValue"), false); } } } @@ -1123,7 +1123,7 @@ protected override void SetItem(string path, object value) { if (path.EndsWith(strPathChk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("NoChangeValue"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("NoChangeValue"), false); return; } @@ -1144,9 +1144,9 @@ protected override void SetItem(string path, object value) { if (!Force) { - string query = helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); + string query = WSManHelper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); query = string.Format(CultureInfo.CurrentCulture, query, currentpluginname); - if (!ShouldContinue(query, helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) + if (!ShouldContinue(query, WSManHelper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) { return; } @@ -1221,7 +1221,7 @@ protected override void SetItem(string path, object value) WSManStringLiterals.containerShell, adjustedChileName); - warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemWarnigForPPQ"), pathForGlobalQuota)); + warningMessage.Add(string.Format(WSManHelper.GetResourceMsgFromResourcetext("SetItemWarnigForPPQ"), pathForGlobalQuota)); } } @@ -1241,11 +1241,11 @@ protected override void SetItem(string path, object value) { if (IsPathLocalMachine(host)) { - warningMessage.Add(helper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarning")); + warningMessage.Add(WSManHelper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarning")); } else { - warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarningRemote"), host)); + warningMessage.Add(string.Format(WSManHelper.GetResourceMsgFromResourcetext("SetItemServiceRestartWarningRemote"), host)); } } } @@ -1259,17 +1259,17 @@ protected override void SetItem(string path, object value) } catch (PSArgumentException) { - AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); return; } catch (PSArgumentNullException) { - AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); return; } catch (NullReferenceException) { - AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); return; } } @@ -1285,14 +1285,14 @@ protected override void SetItem(string path, object value) if (!Force) { string query = string.Empty; - string caption = helper.GetResourceMsgFromResourcetext("SetItemGeneralSecurityCaption"); + string caption = WSManHelper.GetResourceMsgFromResourcetext("SetItemGeneralSecurityCaption"); if (ChildName.Equals("TrustedHosts", StringComparison.OrdinalIgnoreCase)) { - query = helper.GetResourceMsgFromResourcetext("SetItemTrustedHostsWarningQuery"); + query = WSManHelper.GetResourceMsgFromResourcetext("SetItemTrustedHostsWarningQuery"); } else if (ChildName.Equals("RootSDDL", StringComparison.OrdinalIgnoreCase)) { - query = helper.GetResourceMsgFromResourcetext("SetItemRootSDDLWarningQuery"); + query = WSManHelper.GetResourceMsgFromResourcetext("SetItemRootSDDLWarningQuery"); } if (!ShouldContinue(query, caption)) @@ -1318,7 +1318,7 @@ protected override void SetItem(string path, object value) } else { - AssertError(helper.GetResourceMsgFromResourcetext("TrustedHostValueTypeError"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("TrustedHostValueTypeError"), false); } } else @@ -1327,7 +1327,7 @@ protected override void SetItem(string path, object value) if (globalWarningUris.Contains(uri) && globalWarningConfigurations.Contains(ChildName.ToLowerInvariant())) { - warningMessage.Add(string.Format(helper.GetResourceMsgFromResourcetext("SetItemWarningForGlobalQuota"), value)); + warningMessage.Add(string.Format(WSManHelper.GetResourceMsgFromResourcetext("SetItemWarningForGlobalQuota"), value)); } } @@ -1625,7 +1625,7 @@ protected override void RemoveItem(string path, bool recurse) bool throwerror = true; if (path.Length == 0) { - AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); return; } @@ -1645,10 +1645,10 @@ protected override void RemoveItem(string path, bool recurse) { if (ChildName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("LocalHost"), false); } - helper.RemoveFromDictionary(ChildName); + WSManHelper.RemoveFromDictionary(ChildName); return; } @@ -1758,7 +1758,7 @@ protected override void RemoveItem(string path, bool recurse) if (throwerror) { - AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); return; } @@ -1788,7 +1788,7 @@ protected override void RemoveItem(string path, bool recurse) if (throwerror) { - AssertError(helper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("RemoveItemNotSupported"), false); return; } } @@ -1823,7 +1823,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem if (string.IsNullOrEmpty(host)) { - throw new ArgumentException(helper.GetResourceMsgFromResourcetext("InvalidPath")); + throw new ArgumentException(WSManHelper.GetResourceMsgFromResourcetext("InvalidPath")); } // Chk for Winrm Service @@ -1875,7 +1875,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem listenerparams.Add("CertificateThumbPrint", niParams.CertificateThumbPrint); } - NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, listenerparams, WSManStringLiterals.containerListener, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerCaption")); + NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, listenerparams, WSManStringLiterals.containerListener, WSManHelper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerQuery"), WSManHelper.GetResourceMsgFromResourcetext("NewItemShouldContinueListenerCaption")); } else if (path.EndsWith(strPathChk + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) { @@ -1893,11 +1893,11 @@ protected override void NewItem(string path, string itemTypeName, object newItem } Certparams.Add("Enabled", dynParams.Enabled); - NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, Certparams, WSManStringLiterals.containerClientCertificate, helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertQuery"), helper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertCaption")); + NewItemContainerListenerOrCertMapping(sessionobj, path, uri, host, Certparams, WSManStringLiterals.containerClientCertificate, WSManHelper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertQuery"), WSManHelper.GetResourceMsgFromResourcetext("NewItemShouldContinueClientCertCaption")); } else { - AssertError(helper.GetResourceMsgFromResourcetext("NewItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("NewItemNotSupported"), false); return; } } @@ -2115,7 +2115,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h } else { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewItemNotSupported")), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(new InvalidOperationException(WSManHelper.GetResourceMsgFromResourcetext("NewItemNotSupported")), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -2195,9 +2195,9 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h { if (!Force) { - string query = helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); + string query = WSManHelper.GetResourceMsgFromResourcetext("ShouldContinueSecurityQuery"); query = string.Format(CultureInfo.CurrentCulture, query, pName); - if (!ShouldContinue(query, helper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) + if (!ShouldContinue(query, WSManHelper.GetResourceMsgFromResourcetext("ShouldContinueSecurityCaption"))) { return; } @@ -2206,7 +2206,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h PSObject resourceDirProperties = GetItemValue(strPathChk); if ((resourceDirProperties == null) || (resourceDirProperties.Properties["ResourceUri"] == null)) { - string message = helper.FormatResourceMsgFromResourcetext("ResourceURIMissingInResourceDir", + string message = WSManHelper.FormatResourceMsgFromResourcetext("ResourceURIMissingInResourceDir", "ResourceUri", strPathChk); AssertError(message, false); return; // AssertError is going to throw - return silences some static analysis tools @@ -2356,7 +2356,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour if (xmlResource == null) { - AssertError(helper.GetResourceMsgFromResourcetext("InvalidPath"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("InvalidPath"), false); } if (ResourceURI.EndsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) @@ -2370,13 +2370,13 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + parent, StringComparison.OrdinalIgnoreCase)) { - AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); } else { if (!Force) { - if (!ShouldContinue(helper.GetResourceMsgFromResourcetext("SetItemShouldContinueQuery"), helper.GetResourceMsgFromResourcetext("SetItemShouldContinueCaption"))) + if (!ShouldContinue(WSManHelper.GetResourceMsgFromResourcetext("SetItemShouldContinueQuery"), WSManHelper.GetResourceMsgFromResourcetext("SetItemShouldContinueCaption"))) { return; } @@ -2690,7 +2690,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v } else { - AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false); return; } } @@ -4610,10 +4610,10 @@ private void StartWSManService(bool force) { string startserviceScript = string.Format(CultureInfo.InvariantCulture, WSManStringLiterals.StartWinrmServiceSBFormat); ScriptBlock startserviceSb = ScriptBlock.Create(startserviceScript); - Collection result = startserviceSb.Invoke(force, helper.GetResourceMsgFromResourcetext("WSManServiceStartCaption"), helper.GetResourceMsgFromResourcetext("WSManServiceStartQuery")); + Collection result = startserviceSb.Invoke(force, WSManHelper.GetResourceMsgFromResourcetext("WSManServiceStartCaption"), WSManHelper.GetResourceMsgFromResourcetext("WSManServiceStartQuery")); if (!(bool)result[0].ImmediateBaseObject) { - AssertError(helper.GetResourceMsgFromResourcetext("WinRMServiceError"), false); + AssertError(WSManHelper.GetResourceMsgFromResourcetext("WinRMServiceError"), false); } } catch (CmdletInvocationException) @@ -5153,7 +5153,7 @@ private object ValidateAndGetUserObject(string configurationName, object value) else { string error = string.Format( - helper.GetResourceMsgFromResourcetext("InvalidValueType"), + WSManHelper.GetResourceMsgFromResourcetext("InvalidValueType"), WSManStringLiterals.ConfigRunAsPasswordName, typeof(SecureString).FullName); @@ -5174,7 +5174,7 @@ private object ValidateAndGetUserObject(string configurationName, object value) else { string error = string.Format( - helper.GetResourceMsgFromResourcetext("InvalidValueType"), + WSManHelper.GetResourceMsgFromResourcetext("InvalidValueType"), WSManStringLiterals.ConfigRunAsUserName, typeof(PSCredential).FullName); diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index cd5e6d3fc4d..59dcf88c2ea 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -128,7 +128,7 @@ private void DisableClientSideSettings() if (xNode is null) { InvalidOperationException ex = new InvalidOperationException(); - ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(ex, WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -152,7 +152,7 @@ private void DisableClientSideSettings() if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname)) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null); } } catch (System.Xml.XPath.XPathException ex) @@ -194,7 +194,7 @@ private void DisableServerSideSettings() { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, - helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), + WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; @@ -442,7 +442,7 @@ protected override void BeginProcessing() // DelegateComputer cannot be specified when Role is other than client if ((delegatecomputer != null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) { - string message = helper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified", + string message = WSManHelper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified", "DelegateComputer", "Role", Role, @@ -454,7 +454,7 @@ protected override void BeginProcessing() // DelegateComputer must be specified when Role is client if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer == null)) { - string message = helper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified", + string message = WSManHelper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified", "DelegateComputer", "Role", Client); @@ -481,8 +481,8 @@ protected override void BeginProcessing() /// private void EnableClientSideSettings() { - string query = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery"); - string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); + string query = WSManHelper.GetResourceMsgFromResourcetext("CredSSPContinueQuery"); + string caption = WSManHelper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; @@ -498,12 +498,12 @@ private void EnableClientSideSettings() { // get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); - XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); + XmlNode node = WSManHelper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); - ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(ex, WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -535,7 +535,7 @@ private void EnableClientSideSettings() } else { - helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer); } } catch (COMException) @@ -559,8 +559,8 @@ private void EnableClientSideSettings() private void EnableServerSideSettings() { - string query = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery"); - string caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); + string query = WSManHelper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery"); + string caption = WSManHelper.GetResourceMsgFromResourcetext("CredSSPContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; @@ -576,14 +576,14 @@ private void EnableServerSideSettings() { // get the credssp node to check if wsman is configured on this machine string result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); - XmlNode node = helper.GetXmlNode(result, + XmlNode node = WSManHelper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); - ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(ex, WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -817,11 +817,11 @@ protected override void BeginProcessing() IWSManEx wsmanObject = (IWSManEx)new WSManClass(); m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); - XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); + XmlNode node = WSManHelper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); - ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(ex, WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -831,31 +831,31 @@ protected override void BeginProcessing() string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { - WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); + WriteObject(WSManHelper.GetResourceMsgFromResourcetext("NoDelegateFreshCred")); } else { - WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult); + WriteObject(WSManHelper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult); } // Get the server side settings result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); - node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); + node = WSManHelper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); if (node == null) { InvalidOperationException ex = new InvalidOperationException(); - ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); + ErrorRecord er = new ErrorRecord(ex, WSManHelper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); WriteError(er); return; } if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase)) { - WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); + WriteObject(WSManHelper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured")); } else { - WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); + WriteObject(WSManHelper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured")); } } catch (UnauthorizedAccessException ex) diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 16e91cceae9..ebadbf60f08 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -261,7 +261,7 @@ protected override void BeginProcessing() helper.WSManOp = "invoke"; // create the connection string - connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(connectionuri, port, computername, applicationname); } /// diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 25f5bdd5989..33e806e7d2c 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -263,7 +263,7 @@ protected override void BeginProcessing() { if (_proxycredential == null) { - InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred")); + InvalidOperationException ex = new InvalidOperationException(WSManHelper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred")); ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; @@ -272,7 +272,7 @@ protected override void BeginProcessing() if ((_proxycredential != null) && (proxyauthentication == 0)) { - InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth")); + InvalidOperationException ex = new InvalidOperationException(WSManHelper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth")); ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index b9a0e21f1f4..9e400e6f128 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -145,7 +145,7 @@ protected override void ProcessRecord() WSManHelper helper = new WSManHelper(this); IWSManEx wsmanObject = (IWSManEx)new WSManClass(); string connectionStr = string.Empty; - connectionStr = helper.CreateConnectionString(null, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(null, port, computername, applicationname); IWSManSession m_SessionObj = null; try { diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index c318ea76477..e5ee2f70390 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -86,8 +86,8 @@ protected override void BeginProcessing() // If not running elevated, then throw an "elevation required" error message. WSManHelper.ThrowIfNotAdministrator(); helper = new WSManHelper(this); - string query = helper.GetResourceMsgFromResourcetext("QuickConfigContinueQuery"); - string caption = helper.GetResourceMsgFromResourcetext("QuickConfigContinueCaption"); + string query = WSManHelper.GetResourceMsgFromResourcetext("QuickConfigContinueQuery"); + string caption = WSManHelper.GetResourceMsgFromResourcetext("QuickConfigContinueCaption"); if (!force && !ShouldContinue(query, caption)) { return; diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index c83ed7e9e10..6ad55ee4a65 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -277,7 +277,7 @@ protected override void BeginProcessing() } catch (IndexOutOfRangeException) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } @@ -285,7 +285,7 @@ protected override void BeginProcessing() if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.OrdinalIgnoreCase)) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername); } helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); @@ -367,22 +367,22 @@ protected override void BeginProcessing() if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.OrdinalIgnoreCase)) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername); } if (computername.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("LocalHost"), false, computername); } - object _ws = helper.RemoveFromDictionary(computername); + object _ws = WSManHelper.RemoveFromDictionary(computername); if (_ws != null) { Dispose(_ws); } else { - helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); } } } diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index a60ba270104..566a39f2956 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -569,7 +569,7 @@ protected override void ProcessRecord() helper = new WSManHelper(this); helper.WSManOp = "Get"; string connectionStr = null; - connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try @@ -581,7 +581,7 @@ protected override void ProcessRecord() } catch (IndexOutOfRangeException) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } @@ -950,7 +950,7 @@ protected override void ProcessRecord() try { string connectionStr = string.Empty; - connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try @@ -962,7 +962,7 @@ protected override void ProcessRecord() } catch (IndexOutOfRangeException) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } @@ -1245,7 +1245,7 @@ protected override void ProcessRecord() try { string connectionStr = string.Empty; - connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try @@ -1257,7 +1257,7 @@ protected override void ProcessRecord() } catch (IndexOutOfRangeException) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } @@ -1536,7 +1536,7 @@ protected override void BeginProcessing() { helper = new WSManHelper(this); helper.WSManOp = "new"; - connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); + connectionStr = WSManHelper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try @@ -1548,7 +1548,7 @@ protected override void BeginProcessing() } catch (IndexOutOfRangeException) { - helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); + helper.AssertError(WSManHelper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } } diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 000cb871abb..29146150e2c 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -156,7 +156,7 @@ internal static void ThrowIfNotAdministrator() } } - internal string GetResourceMsgFromResourcetext(string rscname) + internal static string GetResourceMsgFromResourcetext(string rscname) { return _resourceMgr.GetString(rscname); } @@ -167,7 +167,7 @@ internal static string FormatResourceMsgFromResourcetextS(string rscname, return FormatResourceMsgFromResourcetextS(_resourceMgr, rscname, args); } - internal string FormatResourceMsgFromResourcetext(string resourceName, + internal static string FormatResourceMsgFromResourcetext(string resourceName, params object[] args) { return FormatResourceMsgFromResourcetextS(_resourceMgr, resourceName, args); @@ -205,7 +205,7 @@ private static string FormatResourceMsgFromResourcetextS( /// /// Connection string. /// Session object. - internal void AddtoDictionary(string key, object value) + internal static void AddtoDictionary(string key, object value) { key = key.ToLowerInvariant(); lock (Sessions.SessionObjCache) @@ -233,7 +233,7 @@ internal void AddtoDictionary(string key, object value) } } - internal object RemoveFromDictionary(string computer) + internal static object RemoveFromDictionary(string computer) { object objsession = null; computer = computer.ToLowerInvariant(); @@ -319,7 +319,7 @@ internal string GetRootNodeName(string operation, string resourceUri, string act return resultStr; } - internal string StripParams(string uri) + internal static string StripParams(string uri) { int pos = uri.IndexOf('?'); if (pos > 0) @@ -505,7 +505,7 @@ internal string GetXmlNs(string resUri) return (@"xmlns:p=""" + StripParams(resUri) + @""""); } - internal XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnamespace) + internal static XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnamespace) { XmlNode node = null; XmlDocument xDoc = new XmlDocument(); @@ -520,7 +520,7 @@ internal XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnam return node; } - internal string CreateConnectionString(Uri ConnUri, int port, string computername, string applicationname) + internal static string CreateConnectionString(Uri ConnUri, int port, string computername, string applicationname) { string ConnectionString = null; if (ConnUri != null) @@ -863,7 +863,7 @@ internal void CleanUp() } } - internal string GetFilterString(Hashtable seletorset) + internal static string GetFilterString(Hashtable seletorset) { StringBuilder filter = new StringBuilder(); foreach (DictionaryEntry entry in seletorset) diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index d99bcbb398b..c0b4db255b1 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -66,7 +66,7 @@ internal sealed class PSTransactionManager : IDisposable /// /// Always return false in CoreCLR /// - internal bool HasTransaction + internal static bool HasTransaction { get { diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index 18b74cbcfe1..7ab056a2e83 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -509,7 +509,7 @@ private void PushGroup(PSObject firstObjectInGroup) /// private void PopGroup() { - GroupEndData endGroup = _viewManager.ViewGenerator.GenerateGroupEndData(); + GroupEndData endGroup = ViewGenerator.GenerateGroupEndData(); this.WriteObject(endGroup); contextManager.Pop(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 8c1c251f149..2ecd30e0e1d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -719,7 +719,7 @@ private ExpressionToken LoadExpressionFromObjectModel(DisplayEntry displayEntry, // For faster startup, we don't validate any of the built-in formatting script blocks, where isFullyTrusted == built-in. if (!LoadingInfo.isFullyTrusted) { - this.expressionFactory.VerifyScriptBlockText(token.expressionValue); + PSPropertyExpressionFactory.VerifyScriptBlockText(token.expressionValue); } } catch (ParseException e) @@ -1924,7 +1924,7 @@ internal bool VerifyScriptBlock(string scriptBlockText) { try { - this.expressionFactory.VerifyScriptBlockText(scriptBlockText); + PSPropertyExpressionFactory.VerifyScriptBlockText(scriptBlockText); } catch (ParseException e) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index f29033e3c8d..748bf07a067 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -283,7 +283,7 @@ internal bool UpdateGroupingKeyValue(PSObject so) return _groupingManager.UpdateGroupingKeyValue(so); } - internal GroupEndData GenerateGroupEndData() + internal static GroupEndData GenerateGroupEndData() { return new GroupEndData(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index 962cf6f5ff1..aa0b78de6d0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -293,7 +293,7 @@ internal bool DeserializeBoolMemberVariable(PSObject so, string property, bool c return val != null && (bool)val; } - internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) + internal static WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) { object wsTypeValue = GetProperty(so, "writeStream"); if (wsTypeValue == null) @@ -563,7 +563,7 @@ internal override void Deserialize(PSObject so, FormatObjectDeserializer deseria base.Deserialize(so, deserializer); this.formatEntryInfo = (FormatEntryInfo)deserializer.DeserializeMandatoryMemberObject(so, "formatEntryInfo"); this.outOfBand = deserializer.DeserializeBoolMemberVariable(so, "outOfBand"); - this.writeStream = deserializer.DeserializeWriteStreamTypeMemberVariable(so); + this.writeStream = FormatObjectDeserializer.DeserializeWriteStreamTypeMemberVariable(so); this.isHelpObject = so.IsHelpObject; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index 7760e86b13d..812099df479 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -561,7 +561,7 @@ internal sealed class StringFormatError : FormattingError internal sealed class PSPropertyExpressionFactory { /// - internal void VerifyScriptBlockText(string scriptText) + internal static void VerifyScriptBlockText(string scriptText) { ScriptBlock.Create(scriptText); } diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 9ac1a28656b..be18d4220da 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -115,7 +115,7 @@ private int GetFuncDescIndex() /// Returns the number of parameters in this property. /// This is applicable only for parameterized properties. /// - internal int ParamCount + internal static int ParamCount { get { diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 2b81c76b6eb..a031f39d6e2 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -37,7 +37,7 @@ public override string ToString() return string.Format(CultureInfo.CurrentCulture, "", Name); } - public string Documentation + public static string Documentation { get { return string.Empty; } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 69f24c243cc..c936797b65d 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -2377,7 +2377,7 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) var switchPair = boundArgument.Value as SwitchPair; if (switchPair != null) { - result[boundArgument.Key] = switchPair.Argument; + result[boundArgument.Key] = SwitchPair.Argument; continue; } // Ignored: diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index c98be4ccac8..a856bb57e72 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -159,7 +159,7 @@ internal SwitchPair(CommandParameterAst parameterAst) /// /// Get the argument. /// - public bool Argument + public static bool Argument { get { return true; } } diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index eb59f9140a2..4ecba7f5ea5 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1061,7 +1061,7 @@ internal string GetBeginBlock() return result; } - internal string GetProcessBlock() + internal static string GetProcessBlock() { return @" try { @@ -1102,7 +1102,7 @@ internal string GetDynamicParamBlock() _wrappedCommandType); } - internal string GetEndBlock() + internal static string GetEndBlock() { return @" try { diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index fb1fe81fc54..267b77da54e 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -270,7 +270,7 @@ protected override void OnRestorePreviousScope() PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet; if (scriptCmdlet != null && !UseLocalScope) { - scriptCmdlet.PopDottedScope(CommandSessionState.CurrentScope); + PSScriptCmdlet.PopDottedScope(CommandSessionState.CurrentScope); } } diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index c6825cc6925..8f370398ab7 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -855,7 +855,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) // Rollback the transaction in the case of errors. if ( - _context.TransactionManager.HasTransaction + PSTransactionManager.HasTransaction && _context.TransactionManager.RollbackPreference != RollbackSeverity.Never ) diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index bf9775b35ef..6f62789b2e9 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -3582,7 +3582,7 @@ private static CacheTable GetInstanceMethodReflectionTable(Type type) } } - internal IEnumerable GetPropertiesAndMethods(Type type, bool @static) + internal static IEnumerable GetPropertiesAndMethods(Type type, bool @static) { CacheTable propertyTable = @static ? GetStaticPropertyReflectionTable(type) @@ -3744,7 +3744,7 @@ protected T GetFirstDotNetEventOrDefault(object obj, MemberNamePredicate pred return null; } - protected T GetFirstDynamicMemberOrDefault(object obj, MemberNamePredicate predicate) where T : PSMemberInfo + protected static T GetFirstDynamicMemberOrDefault(object obj, MemberNamePredicate predicate) where T : PSMemberInfo { var idmop = obj as IDynamicMetaObjectProvider; if (idmop == null || obj is PSObject) @@ -3859,7 +3859,7 @@ internal void AddAllEvents(object obj, PSMemberInfoInternalCollection memb } } - internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo + internal static void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo { var idmop = obj as IDynamicMetaObjectProvider; if (idmop == null || obj is PSObject) diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 69202e6d20e..8b836258fc6 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -110,7 +110,7 @@ internal string PSSnapInName } } - internal string ApplicationBase + internal static string ApplicationBase { get { diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index fd30298669e..68e6be7b71c 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -1954,7 +1954,7 @@ internal PSEventSubscriber( /// private ScriptBlock CreateBoundScriptBlock(ScriptBlock scriptAction) { - ScriptBlock newAction = _context.Modules.CreateBoundScriptBlock(_context, scriptAction, true); + ScriptBlock newAction = ModuleIntrinsics.CreateBoundScriptBlock(_context, scriptAction, true); // Create a new Error variable so that it doesn't pollute the global errors. PSVariable errorVariable = new PSVariable("script:Error", new ArrayList(), ScopedItemOptions.Constant); diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 9bf3318a2c8..9d774e3c5e1 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -409,7 +409,7 @@ internal string RequiresApplicationID } } - internal uint ApplicationIDLineNumber + internal static uint ApplicationIDLineNumber { get { return 0; } } @@ -450,7 +450,7 @@ internal bool RequiresElevation } } - internal uint PSVersionLineNumber + internal static uint PSVersionLineNumber { get { return 0; } } diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index c591a6963ec..499702c67b3 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1156,7 +1156,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri // TODO: Bug 251457. This is a workaround to unblock partners and find out the root cause. Tracing.PSEtwLogProvider provider = new Tracing.PSEtwLogProvider(); - provider.WriteEvent(PSEventId.Engine_Health, + Tracing.PSEtwLogProvider.WriteEvent(PSEventId.Engine_Health, PSChannel.Analytic, PSOpcode.Exception, PSLevel.Informational, diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index d8ed2bc6537..56ba2ccd7bf 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -4029,7 +4029,7 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul /// /// /// - internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSpec, + internal static bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSpec, string rootedModulePath, string extension, out PSModuleInfo nestedModuleInfoIfAvailable) @@ -4435,7 +4435,7 @@ internal enum ModuleLoggingGroupPolicyStatus /// /// Enable Module logging based on group policy. /// - internal void SetModuleLoggingInformation(PSModuleInfo m) + internal static void SetModuleLoggingInformation(PSModuleInfo m) { IEnumerable moduleNames; ModuleLoggingGroupPolicyStatus status = GetModuleLoggingInformation(out moduleNames); @@ -4639,7 +4639,7 @@ internal string FixupFileName(string moduleBase, string name, string extension, /// The base path to use if the file is not rooted. /// The file name to resolve. /// - internal string GetAbsolutePath(string moduleBase, string path) + internal static string GetAbsolutePath(string moduleBase, string path) { if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\'))) { diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index d52374f9b63..7c93da43dab 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -266,7 +266,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object /// The scriptblock to bind. /// Whether it should be linked to the global session state or not. /// A new scriptblock. - internal ScriptBlock CreateBoundScriptBlock(ExecutionContext context, ScriptBlock sb, bool linkToGlobal) + internal static ScriptBlock CreateBoundScriptBlock(ExecutionContext context, ScriptBlock sb, bool linkToGlobal) { PSModuleInfo module = new PSModuleInfo(context, linkToGlobal); return module.NewBoundScriptBlock(sb, context); diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index c9a83a8bb32..6ac8ba6433b 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1986,7 +1986,7 @@ private bool DoShouldContinue( /// public bool TransactionAvailable() { - return UseTransactionFlagSet && Context.TransactionManager.HasTransaction; + return UseTransactionFlagSet && PSTransactionManager.HasTransaction; } /// diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 5703adec664..5f2337ac933 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -196,7 +196,7 @@ public static string GetProcess(CommandMetadata commandMetadata) throw PSTraceSource.NewArgumentNullException("commandMetaData"); } - return commandMetadata.GetProcessBlock(); + return CommandMetadata.GetProcessBlock(); } /// @@ -244,7 +244,7 @@ public static string GetEnd(CommandMetadata commandMetadata) throw PSTraceSource.NewArgumentNullException("commandMetaData"); } - return commandMetadata.GetEndBlock(); + return CommandMetadata.GetEndBlock(); } private static T GetProperty(PSObject obj, string property) where T : class diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index b2d2e3c6837..d5320d2bf36 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4676,7 +4676,7 @@ internal object CopyItemDynamicParameters( if (fileSystemProviders.Count > 0) { providerPath = path; - providerInstance = ExecutionContext.EngineSessionState.GetProviderInstance( + providerInstance = GetProviderInstance( fileSystemProviders[0]); } } diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index a6a7d2efc7f..f4007dc9753 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -274,7 +274,7 @@ internal Provider.CmdletProvider GetProviderInstance(string providerId) /// /// If is null. /// - internal Provider.CmdletProvider GetProviderInstance(ProviderInfo provider) + internal static Provider.CmdletProvider GetProviderInstance(ProviderInfo provider) { if (provider == null) { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index bc443ac10a9..527f1d20bbc 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -2278,7 +2278,7 @@ internal ReadOnlyBag(HashSet hashset) /// /// Indicate if it's a readonly Hashset. /// - public bool IsReadOnly => true; + public static bool IsReadOnly => true; /// /// Check if the set contains an item. diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index ba7548f982d..f9219430eab 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -140,7 +140,7 @@ internal override void DoBeginProcessing() if (mshRuntime != null) { if (mshRuntime.UseTransaction && - (!this.Context.TransactionManager.HasTransaction)) + (!PSTransactionManager.HasTransaction)) { string error = TransactionStrings.NoTransactionStarted; diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index 69346ae303b..5b2a06bc77d 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -19,8 +19,7 @@ class InternalHostRawUserInterface : PSHostRawUserInterface _parentHost = parentHost; } - internal - void + internal static void ThrowNotInteractive() { // It might be interesting to do something like diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 57f3f675ffc..b6cb88cd3e9 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -46,7 +46,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh void ThrowNotInteractive() { - _internalRawUI.ThrowNotInteractive(); + InternalHostRawUserInterface.ThrowNotInteractive(); } private static void diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 14057f05f68..daac76bb0a9 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2399,7 +2399,7 @@ private Expression CaptureStatementResults( return result; } - internal Expression CallAddPipe(Expression expr, Expression pipe) + internal static Expression CallAddPipe(Expression expr, Expression pipe) { if (!PSEnumerableBinder.IsStaticTypePossiblyEnumerable(expr.Type)) { @@ -5620,7 +5620,7 @@ public object VisitThrowStatement(ThrowStatementAst throwStatementAst) #region Expressions - public Expression GenerateCallContains(Expression lhs, Expression rhs, bool ignoreCase) + public static Expression GenerateCallContains(Expression lhs, Expression rhs, bool ignoreCase) { return Expression.Call( CachedReflectionInfo.ParserOps_ContainsOperatorCompiled, @@ -6212,7 +6212,7 @@ public object VisitVariableExpression(VariableExpressionAst variableExpressionAs return GetLocal(tupleIndex); } - internal Expression CompileTypeName(ITypeName typeName, IScriptExtent errorPos) + internal static Expression CompileTypeName(ITypeName typeName, IScriptExtent errorPos) { Type type; try diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 3afc55e9861..2e6e0a2a6c9 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -4049,7 +4049,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && return dynamicKeywordAst; } - internal StatementAst CreateErrorStatementAst( + internal static StatementAst CreateErrorStatementAst( Token functionName, ExpressionAst instanceName, ExpressionAst bodyExpression) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index d1e3c7155d7..f653c12df99 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -100,7 +100,7 @@ internal static IList InferTypeOf( try { context.RuntimePermissions = evalPersmissions; - return context.InferType(ast, new TypeInferenceVisitor(context)).Distinct(new PSTypeNameComparer()).ToList(); + return TypeInferenceContext.InferType(ast, new TypeInferenceVisitor(context)).Distinct(new PSTypeNameComparer()).ToList(); } finally { @@ -249,7 +249,7 @@ internal void AddMembersByInferredTypesClrType(PSTypeName typename, bool isStati var members = isStatic ? PSObject.DotNetStaticAdapter.BaseGetMembers(type) - : PSObject.DotNetInstanceAdapter.GetPropertiesAndMethods(type, false); + : DotNetAdapter.GetPropertiesAndMethods(type, false); if (filterToCall != null) { @@ -395,7 +395,7 @@ internal void AddMembersByInferredTypeCimType(PSTypeName typename, List } } - internal IEnumerable InferType(Ast ast, TypeInferenceVisitor visitor) + internal static IEnumerable InferType(Ast ast, TypeInferenceVisitor visitor) { var res = ast.Accept(visitor); Diagnostics.Assert(res != null, "Fix visit methods to not return null"); @@ -492,7 +492,7 @@ public TypeInferenceVisitor(TypeInferenceContext context) private IEnumerable InferTypes(Ast ast) { - return _context.InferType(ast, this); + return TypeInferenceContext.InferType(ast, this); } object ICustomAstVisitor.VisitTypeExpression(TypeExpressionAst typeExpressionAst) diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 161e53cef0c..3f7fb1b9f9d 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -1077,7 +1077,7 @@ internal void Resync(int start) } } - internal void RemoveTokensFromListDuringResync(List tokenList, int start) + internal static void RemoveTokensFromListDuringResync(List tokenList, int start) { int removeFrom = 0; // If we were saving tokens, remove all tokens from token to the end of the saved tokens. diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 6c7efa68f28..7c0e017c1d9 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -3280,7 +3280,7 @@ internal ErrorRecord FailureErrorRecord /// /// /// - protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException, + protected static void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException, out ErrorRecord failureErrorRecord) { // There are three errors possible diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index d4f5ca427ab..3b0fa20e8a1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -127,7 +127,7 @@ internal string GetMessage(string resourceString) /// /// /// - internal string GetMessage(string resourceString, params object[] args) + internal static string GetMessage(string resourceString, params object[] args) { string message; diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index d4a0a3e7508..79be37c7189 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -526,7 +526,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s if (reason == null) { - reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); + reason = new RuntimeException(GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); } string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError( diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 04ce777964e..28e6a29bfd7 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -313,7 +313,7 @@ public virtual void SetSessionOptions(PSSessionOption options) #region Internal Methods - internal int TimeSpanToTimeOutMs(TimeSpan t) + internal static int TimeSpanToTimeOutMs(TimeSpan t) { if ((t.TotalMilliseconds > int.MaxValue) || (t == TimeSpan.MaxValue) || (t.TotalMilliseconds < 0)) { @@ -2227,7 +2227,7 @@ internal int StartSSHProcess( return StartSSHProcessImpl(startInfo, out stdInWriterVar, out stdOutReaderVar, out stdErrReaderVar); } - internal void KillSSHProcess(int pid) + internal static void KillSSHProcess(int pid) { KillSSHProcessImpl(pid); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 75f70941856..83ecc20fcb2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -1735,7 +1735,7 @@ private void CloseConnection() { try { - _connectionInfo.KillSSHProcess(sshProcessId); + SSHConnectionInfo.KillSSHProcess(sshProcessId); } catch (ArgumentException) { } catch (InvalidOperationException) { } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 9382beb9b31..76320ab1637 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -1250,7 +1250,7 @@ protected internal bool EnsureOptionsComply( /// /// /// - protected internal bool EnsureProtocolVersionComplies( + internal protected static bool EnsureProtocolVersionComplies( WSManNativeApi.WSManPluginRequest requestDetails, string clientVersionString) { diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 2e6db041126..4d9e4c65230 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2429,7 +2429,7 @@ internal void SetLocalsTupleForNewScope(SessionStateScope scope) /// /// If the script cmdlet is dotted, this method is used to pop the locals from the 'DottedScopes' of the current scope. /// - internal void PopDottedScope(SessionStateScope scope) => scope.DottedScopes.Pop(); + internal static void PopDottedScope(SessionStateScope scope) => scope.DottedScopes.Pop(); internal void PrepareForBinding(CommandLineParameters commandLineParameters) { diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 49d1e67e5d9..019a8ba8c49 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -508,7 +508,7 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // Win8: 572882 When the system locale is English and the UI is JPN, // running "update-help" still downs English help content. - var cultures = _language ?? _helpSystem.GetCurrentUICulture(); + var cultures = _language ?? UpdatableHelpSystem.GetCurrentUICulture(); foreach (string culture in cultures) { @@ -639,7 +639,7 @@ internal Dictionary, UpdatableHelpModuleInfo> GetModuleIn /// Current culture. /// Force update. /// True if it is necessary to update help, false if not. - internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo, + internal static bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo, UpdatableHelpInfo newHelpInfo, CultureInfo culture, bool force) { Debug.Assert(module != null); @@ -804,7 +804,7 @@ private IEnumerable RecursiveResolvePathHelper(string path) /// Validates the provider of the path, only FileSystem provider is accepted. /// /// Path to validate. - internal void ValidatePathProvider(PathInfo path) + internal static void ValidatePathProvider(PathInfo path) { if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName) { diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 31fe5362d77..a2b71563330 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -290,7 +290,7 @@ public void Dispose() /// Gets the current UIculture (includes the fallback chain) /// /// A list of cultures. - internal IEnumerable GetCurrentUICulture() + internal static IEnumerable GetCurrentUICulture() { CultureInfo culture = CultureInfo.CurrentUICulture; @@ -1498,7 +1498,7 @@ internal static string GetFilePath(string path) /// Gets the default source path from GP. /// /// - internal string GetDefaultSourcePath() + internal static string GetDefaultSourcePath() { var updatableHelpSetting = Utils.GetPolicySetting(Utils.SystemWideOnlyConfig); string defaultSourcePath = updatableHelpSetting?.DefaultSourcePath; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 01b17cbad7e..d549748c0d0 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -146,7 +146,7 @@ protected override void BeginProcessing() if (_path == null) { // Pull default source path from GP - string defaultSourcePath = _helpSystem.GetDefaultSourcePath(); + string defaultSourcePath = UpdatableHelpSystem.GetDefaultSourcePath(); if (defaultSourcePath != null) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index a32dc421748..bee651745b0 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -359,7 +359,7 @@ public string GetHelpMaml(string helpItemName, string path) XmlDocument document = new XmlDocument(); CultureInfo currentUICulture = CultureInfo.CurrentUICulture; string fullHelpPath = Path.Combine( - string.IsNullOrEmpty(this.ProviderInfo.ApplicationBase) ? string.Empty : this.ProviderInfo.ApplicationBase, + string.IsNullOrEmpty(ProviderInfo.ApplicationBase) ? string.Empty : ProviderInfo.ApplicationBase, currentUICulture.ToString(), string.IsNullOrEmpty(this.ProviderInfo.HelpFile) ? string.Empty : this.ProviderInfo.HelpFile); diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index ca8471749eb..f3e70b5d71f 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -140,7 +140,7 @@ internal static void LogSettingsEvent(LogContext logContext, string variableName /// internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -153,7 +153,7 @@ internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PS /// internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -166,7 +166,7 @@ internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -179,7 +179,7 @@ internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); } /// @@ -192,7 +192,7 @@ internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task /// internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -216,12 +216,12 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta UInt32 fragmentLength, PSETWBinaryBlob fragmentData) { - if (provider.IsEnabled(PSLevel.Verbose, keyword)) + if (PSEtwLogProvider.IsEnabled(PSLevel.Verbose, keyword)) { string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", string.Empty)); - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, payLoadData); } @@ -237,7 +237,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -250,7 +250,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -263,7 +263,7 @@ internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PST /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); } /// @@ -281,14 +281,14 @@ internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask t internal static void SetActivityIdForCurrentThread(Guid newActivityId) { - provider.SetActivityIdForCurrentThread(newActivityId); + PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); } internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { // set the new activity id - provider.SetActivityIdForCurrentThread(newActivityId); + PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); // Once the activity id is set, write the transfer event WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); @@ -308,10 +308,10 @@ internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, + PSEtwLogProvider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysOperational); - provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, + PSEtwLogProvider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysAnalytic); } @@ -321,7 +321,7 @@ internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventF /// internal static void WriteTransferEvent(Guid parentActivityId) { - provider.WriteTransferEvent(parentActivityId); + PSEtwLogProvider.WriteTransferEvent(parentActivityId); } } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index a13dac02e15..ce8c6697af3 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -39,7 +39,7 @@ static PSEtwLogProvider() /// may want to call this function if the provider needs to perform extra work to generate the event. In this case, /// calling this function first to determine if a session requested the event or not, may save resources and time. /// - internal bool IsEnabled(PSLevel level, PSKeyword keywords) + internal static bool IsEnabled(PSLevel level, PSKeyword keywords) { return etwProvider.IsEnabled((byte)level, (long)keywords); } @@ -267,7 +267,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTas /// /// /// - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) { long longKeyword = 0x00; @@ -290,7 +290,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev /// /// Writes an activity transfer event. /// - internal void WriteTransferEvent(Guid parentActivityId) + internal static void WriteTransferEvent(Guid parentActivityId) { etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } @@ -298,7 +298,7 @@ internal void WriteTransferEvent(Guid parentActivityId) /// /// /// - internal void SetActivityIdForCurrentThread(Guid newActivityId) + internal static void SetActivityIdForCurrentThread(Guid newActivityId) { Guid result = newActivityId; EventProvider.SetActivityId(ref result); diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 54e69da68f0..efdfb71b2ec 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -245,7 +245,7 @@ internal void CompareConsoleSessionConfiguration(ConsoleSessionConfiguration a, } } - internal void CompareTwoPolicies(PowerShellPolicies a, PowerShellPolicies b) + internal static void CompareTwoPolicies(PowerShellPolicies a, PowerShellPolicies b) { // Compare 'ScriptExecution' settings CompareScriptExecution(a.ScriptExecution, b.ScriptExecution); @@ -387,7 +387,7 @@ private static void CreateBrokenConfigFile(string fileName) File.WriteAllText(fileName, "[abbra"); } - internal void ForceReadingFromFile() + internal static void ForceReadingFromFile() { // Reset the cached roots. FieldInfo roots = typeof(PowerShellConfig).GetField("configRoots", BindingFlags.NonPublic | BindingFlags.Instance); @@ -412,7 +412,7 @@ public PowerShellPolicyTests(PowerShellPolicyFixture fixture) public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotEmpty() { fixture.SetupConfigFile1(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers); var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser); @@ -428,7 +428,7 @@ public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotEmpty() public void PowerShellConfig_GetPowerShellPolicies_EmptyUserConfig() { fixture.SetupConfigFile2(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers); var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser); @@ -443,7 +443,7 @@ public void PowerShellConfig_GetPowerShellPolicies_EmptyUserConfig() public void PowerShellConfig_GetPowerShellPolicies_EmptySystemConfig() { fixture.SetupConfigFile3(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers); var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser); @@ -458,7 +458,7 @@ public void PowerShellConfig_GetPowerShellPolicies_EmptySystemConfig() public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesEmpty() { fixture.SetupConfigFile4(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers); var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser); @@ -471,7 +471,7 @@ public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesEmpty() public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotExist() { fixture.CleanupConfigFiles(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); var sysPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers); var userPolicies = PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser); @@ -484,7 +484,7 @@ public void PowerShellConfig_GetPowerShellPolicies_BothConfigFilesNotExist() public void Utils_GetPolicySetting_BothConfigFilesNotEmpty() { fixture.SetupConfigFile1(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); ScriptExecution scriptExecution; scriptExecution = Utils.GetPolicySetting(Utils.SystemWideOnlyConfig); @@ -583,7 +583,7 @@ public void Utils_GetPolicySetting_BothConfigFilesNotEmpty() public void Utils_GetPolicySetting_EmptyUserConfig() { fixture.SetupConfigFile2(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); // The CurrentUser config is empty ScriptExecution scriptExecution; @@ -682,7 +682,7 @@ public void Utils_GetPolicySetting_EmptyUserConfig() public void Utils_GetPolicySetting_EmptySystemConfig() { fixture.SetupConfigFile3(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); // The SystemWide config is empty ScriptExecution scriptExecution; @@ -782,7 +782,7 @@ public void Utils_GetPolicySetting_EmptySystemConfig() public void Utils_GetPolicySetting_BothConfigFilesEmpty() { fixture.SetupConfigFile4(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); // Both config files are empty ScriptExecution scriptExecution; @@ -882,7 +882,7 @@ public void Utils_GetPolicySetting_BothConfigFilesEmpty() public void Utils_GetPolicySetting_BothConfigFilesNotExist() { fixture.CleanupConfigFiles(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); // Both config files don't exist ScriptExecution scriptExecution; @@ -982,7 +982,7 @@ public void Utils_GetPolicySetting_BothConfigFilesNotExist() public void PowerShellConfig_GetPowerShellPolicies_BrokenSystemConfig() { fixture.SetupConfigFile5(); - fixture.ForceReadingFromFile(); + PowerShellPolicyFixture.ForceReadingFromFile(); Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers)); Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser)); diff --git a/test/xUnit/csharp/test_Prediction.cs b/test/xUnit/csharp/test_Prediction.cs index a2c38db1359..5c9e1975a2d 100644 --- a/test/xUnit/csharp/test_Prediction.cs +++ b/test/xUnit/csharp/test_Prediction.cs @@ -71,7 +71,7 @@ public void Clear() public string Description => _description; - bool ICommandPredictor.CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => true; + static bool ICommandPredictor.CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => true; public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) { From 671ca15581556d9815eb08b20c3a575b71883480 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 22:44:20 +0100 Subject: [PATCH 02/12] Fix CA1000 --- src/System.Management.Automation/engine/Utils.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 527f1d20bbc..34610eace64 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -2278,7 +2278,9 @@ internal ReadOnlyBag(HashSet hashset) /// /// Indicate if it's a readonly Hashset. /// - public static bool IsReadOnly => true; +#pragma warning disable CA1822 // Mark members as static + public bool IsReadOnly => true; +#pragma warning restore CA1822 // https://github.com/dotnet/roslyn-analyzers/issues/5320 /// /// Check if the set contains an item. From c36099d308467aaed6110ac1bd114ec430d68c6f Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 22:52:54 +0100 Subject: [PATCH 03/12] Fix IDE0036 --- .../engine/remoting/fanin/WSManPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 76320ab1637..353de364a66 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -1250,7 +1250,7 @@ protected internal bool EnsureOptionsComply( /// /// /// - internal protected static bool EnsureProtocolVersionComplies( + protected internal static bool EnsureProtocolVersionComplies( WSManNativeApi.WSManPluginRequest requestDetails, string clientVersionString) { From ee83e60324c1f7b8aed15532582058fd3acf0ee3 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 23:00:32 +0100 Subject: [PATCH 04/12] Fix CA1822 --- .../utility/ImplicitRemotingCommands.cs | 50 +++++++++---------- .../commands/utility/Join-String.cs | 2 +- .../InvokeWSManAction.cs | 2 +- .../WSManInstance.cs | 6 +-- src/Microsoft.WSMan.Management/WsManHelper.cs | 6 +-- .../engine/SessionStateProviderAPIs.cs | 8 +-- .../hostifaces/InternalHostUserInterface.cs | 3 +- .../remoting/commands/PSRemotingCmdlet.cs | 2 +- .../engine/remoting/fanin/WSManPlugin.cs | 2 +- .../namespaces/LocationGlobber.cs | 6 +-- .../utils/tracing/PSEtwLog.cs | 2 +- .../utils/tracing/PSEtwLogProvider.cs | 2 +- 12 files changed, 45 insertions(+), 46 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index cad363346f4..7058dadee5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -557,7 +557,7 @@ internal static ErrorDetails GetErrorDetails(string errorId, params object[] arg args); } - private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() + private static ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() { const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; @@ -573,7 +573,7 @@ private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() return errorRecord; } - private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) + private static ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) { if (string.IsNullOrEmpty(commandName)) { @@ -594,7 +594,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) return errorRecord; } - private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames) + private static ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames) { if (string.IsNullOrEmpty(commandNames)) { @@ -615,7 +615,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames return errorRecord; } - private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) + private static ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) { if (string.IsNullOrEmpty(commandName)) { @@ -636,7 +636,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) return errorRecord; } - private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) + private static ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) { if (string.IsNullOrEmpty(typeName)) { @@ -657,7 +657,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) return errorRecord; } - private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) + private static ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) { if (string.IsNullOrEmpty(commandName)) { @@ -678,7 +678,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) return errorRecord; } - private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, string nameType, string name) + private static ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, string nameType, string name) { if (string.IsNullOrEmpty(commandName)) { @@ -764,7 +764,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti return errorRecord; } - private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) + private static ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) { if (string.IsNullOrEmpty(aliasName)) { @@ -785,7 +785,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) return errorRecord; } - private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) + private static ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) { if (string.IsNullOrEmpty(commandName)) { @@ -813,7 +813,7 @@ private void ReportSkippedCommands() if (_commandsSkippedBecauseOfShadowing.Count != 0) { string skippedCommands = string.Join(", ", _commandsSkippedBecauseOfShadowing.ToArray()); - ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands); + ErrorRecord errorRecord = GetErrorCommandSkippedBecauseOfShadowing(skippedCommands); this.WriteWarning(errorRecord.ErrorDetails.Message); } } @@ -999,14 +999,14 @@ private T ConvertTo(string commandName, object value, bool nullOk) } else { - this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + this.ThrowTerminatingError(GetErrorMalformedDataFromRemoteCommand(commandName)); } } T t; if (!LanguagePrimitives.TryConvertTo(value, out t)) { - this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + this.ThrowTerminatingError(GetErrorMalformedDataFromRemoteCommand(commandName)); } return t; @@ -1022,7 +1022,7 @@ private T GetPropertyValue(string commandName, PSObject pso, string propertyN PSPropertyInfo property = pso.Properties[propertyName]; if (property == null) { - this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); + this.ThrowTerminatingError(GetErrorMalformedDataFromRemoteCommand(commandName)); } return ConvertTo(commandName, property.Value, nullOk); @@ -1188,20 +1188,20 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) { if (!IsCommandNameMatchingParameters(commandMetadata.Name)) { - this.WriteError(this.GetErrorSkippedNonRequestedCommand(commandMetadata.Name)); + this.WriteError(GetErrorSkippedNonRequestedCommand(commandMetadata.Name)); return false; } if (!IsSafeNameOrIdentifier(commandMetadata.Name)) { - this.WriteError(this.GetErrorSkippedUnsafeCommandName(commandMetadata.Name)); + this.WriteError(GetErrorSkippedUnsafeCommandName(commandMetadata.Name)); return false; } if ((commandMetadata.DefaultParameterSetName != null) && !IsSafeNameOrIdentifier(commandMetadata.DefaultParameterSetName)) { - this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + this.WriteError(GetErrorSkippedUnsafeNameInMetadata( commandMetadata.Name, "ParameterSet", commandMetadata.DefaultParameterSetName)); @@ -1226,7 +1226,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) if (!IsSafeParameterName(parameter.Name)) { - this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + this.WriteError(GetErrorSkippedUnsafeNameInMetadata( commandMetadata.Name, "Parameter", parameter.Name)); @@ -1239,7 +1239,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) { if (!IsSafeNameOrIdentifier(alias)) { - this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + this.WriteError(GetErrorSkippedUnsafeNameInMetadata( commandMetadata.Name, "Alias", alias)); @@ -1254,7 +1254,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) { if (!IsSafeNameOrIdentifier(setPair.Key)) { - this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( + this.WriteError(GetErrorSkippedUnsafeNameInMetadata( commandMetadata.Name, "ParameterSet", setPair.Key)); @@ -1341,7 +1341,7 @@ private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInf resolvedCommandName = GetPropertyValue("Get-Command", deserializedCommandInfo, "ResolvedCommandName", true); if (string.IsNullOrEmpty(resolvedCommandName)) { - this.WriteError(this.GetErrorCouldntResolvedAlias(name)); + this.WriteError(GetErrorCouldntResolvedAlias(name)); } } else @@ -1421,7 +1421,7 @@ private void AddRemoteCommandMetadata( if (resolvedCommandName != null && !IsSafeNameOrIdentifier(commandMetadata.Name)) { - this.WriteError(this.GetErrorSkippedUnsafeCommandName(resolvedCommandName)); + this.WriteError(GetErrorSkippedUnsafeCommandName(resolvedCommandName)); return; } @@ -1468,7 +1468,7 @@ private bool IsSafeTypeDefinition(ExtendedTypeDefinition typeDefinition) { if (!IsTypeNameMatchingParameters(typeDefinition.TypeName)) { - this.WriteError(this.GetErrorSkippedNonRequestedTypeDefinition(typeDefinition.TypeName)); + this.WriteError(GetErrorSkippedNonRequestedTypeDefinition(typeDefinition.TypeName)); return false; } @@ -1644,7 +1644,7 @@ internal List GetRemoteFormatData() if ((numberOfReceivedObjects == 0) && (_formatTypeNamesSpecified)) { - this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-FormatData")); + this.ThrowTerminatingError(GetErrorNoResultsFromRemoteEnd("Get-FormatData")); } return result; @@ -1770,7 +1770,7 @@ internal List GetRemoteCommandMetadata(out Dictionary(name2commandMetadata.Values); @@ -1889,7 +1889,7 @@ internal List GenerateProxyModule( if (listOfCommandMetadata.Count == 0) { - ErrorRecord error = this.GetErrorNoCommandsImportedBecauseOfSkipping(); + ErrorRecord error = GetErrorNoCommandsImportedBecauseOfSkipping(); this.ThrowTerminatingError(error); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index 68e0408f8ec..5f751e307eb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -201,7 +201,7 @@ void AddMatching(string completionText) return res; } - private IEnumerable CompleteSeparator(string wordToComplete) + private static IEnumerable CompleteSeparator(string wordToComplete) { var res = new List(10); diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index ebadbf60f08..9e849d1f5e1 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -277,7 +277,7 @@ protected override void ProcessRecord() // create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); - string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); + string rootNode = WSManHelper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); string resultXml = m_session.Invoke(action, m_resource, input, 0); diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 566a39f2956..d831b4e9a9a 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -968,7 +968,7 @@ protected override void ProcessRecord() IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); - string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); + string rootNode = WSManHelper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); XmlDocument xmldoc = new XmlDocument(); @@ -1263,7 +1263,7 @@ protected override void ProcessRecord() IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); - string ResourceURI = helper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); + string ResourceURI = WSManHelper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); try { ((IWSManSession)m_session).Delete(ResourceURI, 0); @@ -1563,7 +1563,7 @@ protected override void ProcessRecord() IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); // create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); - string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); + string rootNode = WSManHelper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); try diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 29146150e2c..f42d75b6921 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -288,7 +288,7 @@ internal static Dictionary GetSessionObjCache() return Sessions.SessionObjCache; } - internal string GetRootNodeName(string operation, string resourceUri, string actionStr) + internal static string GetRootNodeName(string operation, string resourceUri, string actionStr) { string resultStr = null, sfx = null; if (resourceUri != null) @@ -500,7 +500,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, return resultString; } - internal string GetXmlNs(string resUri) + internal static string GetXmlNs(string resUri) { return (@"xmlns:p=""" + StripParams(resUri) + @""""); } @@ -913,7 +913,7 @@ internal void AssertError(string ErrorMessage, bool IsWSManError, object targeto } } - internal string GetURIWithFilter(string uri, string filter, Hashtable selectorset, string operation) + internal static string GetURIWithFilter(string uri, string filter, Hashtable selectorset, string operation) { StringBuilder sburi = new StringBuilder(); sburi.Append(uri); diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index f4007dc9753..f22aa246ee4 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -375,7 +375,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId) /// if the is not for a provider /// that is derived from NavigationCmdletProvider. /// - internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) + internal static DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) { if (provider == null) { @@ -474,7 +474,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId) /// if the is not for a provider /// that is derived from NavigationCmdletProvider. /// - internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) + internal static ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) { if (provider == null) { @@ -573,7 +573,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) /// if the is not for a provider /// that is derived from NavigationCmdletProvider. /// - internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provider) + internal static ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provider) { if (provider == null) { @@ -637,7 +637,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid /// if the is not for a provider /// that is derived from NavigationCmdletProvider. /// - internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo provider) + internal static NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo provider) { if (provider == null) { diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index b6cb88cd3e9..1d27286c2f5 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -42,8 +42,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh _internalRawUI = new InternalHostRawUserInterface(rawui, _parent); } - private - void + private static void ThrowNotInteractive() { InternalHostRawUserInterface.ThrowNotInteractive(); diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 3b0fa20e8a1..348a11ecd1d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -115,7 +115,7 @@ protected string ResolveComputerName(string computerName) /// resource String which holds the message /// /// Error message loaded from appropriate resource cache. - internal string GetMessage(string resourceString) + internal static string GetMessage(string resourceString) { string message = GetMessage(resourceString, null); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 353de364a66..81068b5a485 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -1191,7 +1191,7 @@ private static IntPtr GetRunAsClientToken() /// /// /// - protected internal bool EnsureOptionsComply( + internal protected static bool EnsureOptionsComply( WSManNativeApi.WSManPluginRequest requestDetails) { WSManNativeApi.WSManOption[] options = requestDetails.operationInfo.optionSet.options; diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index e4ab1f3cfc5..366a23bb721 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -459,7 +459,7 @@ private Collection ResolveDriveQualifiedPath( // Associate the drive with the context context.Drive = drive; - providerInstance = _sessionState.Internal.GetContainerProviderInstance(drive.Provider); + providerInstance = SessionStateInternal.GetContainerProviderInstance(drive.Provider); ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider; ItemCmdletProvider itemProvider = providerInstance as ItemCmdletProvider; @@ -1921,7 +1921,7 @@ internal string GetDriveRootRelativePathFromPSPath( try { providerInstance = - _sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider); + SessionStateInternal.GetContainerProviderInstance(workingDriveForPath.Provider); // Add the drive info to the context so that downstream methods // have access to it. @@ -1958,7 +1958,7 @@ CmdletProviderContext context string childPath = string.Empty; CmdletProvider providerInstance = - _sessionState.Internal.GetContainerProviderInstance(drive.Provider); + SessionStateInternal.GetContainerProviderInstance(drive.Provider); NavigationCmdletProvider navigationProvider = providerInstance as NavigationCmdletProvider; // Normalize the paths diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index f3e70b5d71f..a2191fa64a1 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -276,7 +276,7 @@ internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask t /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { - provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); } internal static void SetActivityIdForCurrentThread(Guid newActivityId) diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index ce8c6697af3..d288cb11516 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -251,7 +251,7 @@ internal override bool UseLoggingVariables() /// /// Log context. /// - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { WriteEvent(id, channel, opcode, GetPSLevelFromSeverity(logContext.Severity), task, (PSKeyword)0x0, LogContextToString(logContext), GetPSLogUserData(logContext.ExecutionContext), payLoad); From e638e6635994af2fd2cca3ad8ae58ef57ceded76 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 23:01:41 +0100 Subject: [PATCH 05/12] Fix IDE0036 --- .../engine/remoting/fanin/WSManPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 81068b5a485..84f8bce8e5d 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -1191,7 +1191,7 @@ private static IntPtr GetRunAsClientToken() /// /// /// - internal protected static bool EnsureOptionsComply( + protected internal static bool EnsureOptionsComply( WSManNativeApi.WSManPluginRequest requestDetails) { WSManNativeApi.WSManOption[] options = requestDetails.operationInfo.optionSet.options; From 5c212ae7fe8f328a60ebdfe0824c4d2f47415763 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Wed, 28 Jul 2021 23:20:37 +0100 Subject: [PATCH 06/12] Suppress CA1822 for Dispose method --- .../engine/remoting/client/ClientRemotePowerShell.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 4ea06ea2feb..5af0b6f68a4 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -951,7 +951,8 @@ public void Dispose() /// Release all resources. /// /// If true, release all managed resources. - protected void Dispose(bool disposing) +#pragma warning disable CA1822 // Mark members as static + protected static void Dispose(bool disposing) { if (disposing) { @@ -960,6 +961,7 @@ protected void Dispose(bool disposing) // errorstream.Dispose(); } } +#pragma warning restore CA1822 // https://github.com/dotnet/roslyn-analyzers/issues/5323 #endregion IDisposable } From 3fb65fd419be9335bbba8dee2a32f72c516ae264 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 00:33:24 +0100 Subject: [PATCH 07/12] Fix CA1822 --- .../GetCounterCommand.cs | 2 +- src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 568316c4f0a..15561e57ed8 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -422,7 +422,7 @@ private void ProcessGetCounter() string localizedPath = path; if (_defaultCounters) { - res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath); + res = PdhHelper.TranslateLocalCounterPath(path, out localizedPath); if (res != PdhResults.PDH_CSTATUS_VALID_DATA) { string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index dfddaa6b0a4..a35119b5daf 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -927,7 +927,7 @@ private static uint ParsePath(string fullPath, ref PDH_COUNTER_PATH_ELEMENTS pCo // requires a different firewall exception. // This function checks and Asserts if the path is not valid. // - public uint TranslateLocalCounterPath(string englishPath, out string localizedPath) + public static uint TranslateLocalCounterPath(string englishPath, out string localizedPath) { uint res = PdhResults.PDH_CSTATUS_VALID_DATA; localizedPath = string.Empty; From f62ab424ea0816a5ee68b4d7293513fcb69aac04 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 02:32:56 +0100 Subject: [PATCH 08/12] Remove redundant preprocessor directives --- .../engine/interpreter/InstructionList.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index cbf831f3377..2ad8e0707a5 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -232,7 +232,6 @@ private void UpdateStackDepth(Instruction instruction) [Conditional("DEBUG")] public void SetDebugCookie(object cookie) { -#if DEBUG if (_debugCookies == null) { _debugCookies = new List>(); @@ -240,7 +239,6 @@ public void SetDebugCookie(object cookie) Debug.Assert(Count > 0); _debugCookies.Add(new KeyValuePair(Count - 1, cookie)); -#endif } public int Count From 73f1d1bdd4e2d2ed9fcde7deefc4eb3661a963b3 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 17:22:05 +0100 Subject: [PATCH 09/12] Revert and suppress CA1822 due to conditional compilation issue --- .../engine/ManagementObjectAdapter.cs | 2 +- .../engine/SecurityManagerBase.cs | 5 +++ .../utils/tracing/PSEtwLog.cs | 32 +++++++++---------- .../utils/tracing/PSEtwLogProvider.cs | 31 +++++++++++++++--- 4 files changed, 48 insertions(+), 22 deletions(-) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 499702c67b3..c591a6963ec 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1156,7 +1156,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri // TODO: Bug 251457. This is a workaround to unblock partners and find out the root cause. Tracing.PSEtwLogProvider provider = new Tracing.PSEtwLogProvider(); - Tracing.PSEtwLogProvider.WriteEvent(PSEventId.Engine_Health, + provider.WriteEvent(PSEventId.Engine_Health, PSChannel.Analytic, PSOpcode.Exception, PSLevel.Informational, diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 31712949cf7..fd2dcac6dbc 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Host; using Dbg = System.Management.Automation; @@ -72,6 +73,10 @@ public AuthorizationManager(string shellId) /// If the derived security manager threw an exception or returned /// false with a reason. /// + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] internal void ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host) diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index a2191fa64a1..ca8471749eb 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -140,7 +140,7 @@ internal static void LogSettingsEvent(LogContext logContext, string variableName /// internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -153,7 +153,7 @@ internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PS /// internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -166,7 +166,7 @@ internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -179,7 +179,7 @@ internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); } /// @@ -192,7 +192,7 @@ internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task /// internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -216,12 +216,12 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta UInt32 fragmentLength, PSETWBinaryBlob fragmentData) { - if (PSEtwLogProvider.IsEnabled(PSLevel.Verbose, keyword)) + if (provider.IsEnabled(PSLevel.Verbose, keyword)) { string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", string.Empty)); - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, payLoadData); } @@ -237,7 +237,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -250,7 +250,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -263,7 +263,7 @@ internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PST /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); } /// @@ -276,19 +276,19 @@ internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask t /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); + provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); } internal static void SetActivityIdForCurrentThread(Guid newActivityId) { - PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); + provider.SetActivityIdForCurrentThread(newActivityId); } internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { // set the new activity id - PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); + provider.SetActivityIdForCurrentThread(newActivityId); // Once the activity id is set, write the transfer event WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); @@ -308,10 +308,10 @@ internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - PSEtwLogProvider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, + provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysOperational); - PSEtwLogProvider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, + provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysAnalytic); } @@ -321,7 +321,7 @@ internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventF /// internal static void WriteTransferEvent(Guid parentActivityId) { - PSEtwLogProvider.WriteTransferEvent(parentActivityId); + provider.WriteTransferEvent(parentActivityId); } } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index d288cb11516..5a6f72d3df7 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -7,6 +7,7 @@ using System.Management.Automation.Internal; using System.Text; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Tracing { @@ -39,7 +40,11 @@ static PSEtwLogProvider() /// may want to call this function if the provider needs to perform extra work to generate the event. In this case, /// calling this function first to determine if a session requested the event or not, may save resources and time. /// - internal static bool IsEnabled(PSLevel level, PSKeyword keywords) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal bool IsEnabled(PSLevel level, PSKeyword keywords) { return etwProvider.IsEnabled((byte)level, (long)keywords); } @@ -251,7 +256,11 @@ internal override bool UseLoggingVariables() /// /// Log context. /// - internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { WriteEvent(id, channel, opcode, GetPSLevelFromSeverity(logContext.Severity), task, (PSKeyword)0x0, LogContextToString(logContext), GetPSLogUserData(logContext.ExecutionContext), payLoad); @@ -267,7 +276,11 @@ internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode /// /// /// - internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) { long longKeyword = 0x00; @@ -290,7 +303,11 @@ internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode /// /// Writes an activity transfer event. /// - internal static void WriteTransferEvent(Guid parentActivityId) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteTransferEvent(Guid parentActivityId) { etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } @@ -298,7 +315,11 @@ internal static void WriteTransferEvent(Guid parentActivityId) /// /// /// - internal static void SetActivityIdForCurrentThread(Guid newActivityId) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void SetActivityIdForCurrentThread(Guid newActivityId) { Guid result = newActivityId; EventProvider.SetActivityId(ref result); From e141d56ea11c644e735a540cda1272913c98a846 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 18:39:54 +0100 Subject: [PATCH 10/12] fixup! 73f1d1bdd --- .../engine/ManagementObjectAdapter.cs | 2 +- .../utils/tracing/PSEtwLog.cs | 32 +++++++++---------- .../utils/tracing/PSEtwLogProvider.cs | 30 +++-------------- .../utils/tracing/PSSysLogProvider.cs | 14 ++++---- .../utils/tracing/SysLogProvider.cs | 4 +-- 5 files changed, 31 insertions(+), 51 deletions(-) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index c591a6963ec..499702c67b3 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1156,7 +1156,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri // TODO: Bug 251457. This is a workaround to unblock partners and find out the root cause. Tracing.PSEtwLogProvider provider = new Tracing.PSEtwLogProvider(); - provider.WriteEvent(PSEventId.Engine_Health, + Tracing.PSEtwLogProvider.WriteEvent(PSEventId.Engine_Health, PSChannel.Analytic, PSOpcode.Exception, PSLevel.Informational, diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index ca8471749eb..a2191fa64a1 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -140,7 +140,7 @@ internal static void LogSettingsEvent(LogContext logContext, string variableName /// internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -153,7 +153,7 @@ internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PS /// internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -166,7 +166,7 @@ internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -179,7 +179,7 @@ internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); } /// @@ -192,7 +192,7 @@ internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task /// internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -216,12 +216,12 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta UInt32 fragmentLength, PSETWBinaryBlob fragmentData) { - if (provider.IsEnabled(PSLevel.Verbose, keyword)) + if (PSEtwLogProvider.IsEnabled(PSLevel.Verbose, keyword)) { string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", string.Empty)); - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, payLoadData); } @@ -237,7 +237,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -250,7 +250,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -263,7 +263,7 @@ internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PST /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); } /// @@ -276,19 +276,19 @@ internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask t /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { - provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); + PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); } internal static void SetActivityIdForCurrentThread(Guid newActivityId) { - provider.SetActivityIdForCurrentThread(newActivityId); + PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); } internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { // set the new activity id - provider.SetActivityIdForCurrentThread(newActivityId); + PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); // Once the activity id is set, write the transfer event WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); @@ -308,10 +308,10 @@ internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, + PSEtwLogProvider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysOperational); - provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, + PSEtwLogProvider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysAnalytic); } @@ -321,7 +321,7 @@ internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventF /// internal static void WriteTransferEvent(Guid parentActivityId) { - provider.WriteTransferEvent(parentActivityId); + PSEtwLogProvider.WriteTransferEvent(parentActivityId); } } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 5a6f72d3df7..23834626f4b 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -40,11 +40,7 @@ static PSEtwLogProvider() /// may want to call this function if the provider needs to perform extra work to generate the event. In this case, /// calling this function first to determine if a session requested the event or not, may save resources and time. /// - [SuppressMessage( - "Performance", - "CA1822:Mark members as static", - Justification = "Issue with conditional compilation using UNIX symbol.")] - internal bool IsEnabled(PSLevel level, PSKeyword keywords) + internal static bool IsEnabled(PSLevel level, PSKeyword keywords) { return etwProvider.IsEnabled((byte)level, (long)keywords); } @@ -256,11 +252,7 @@ internal override bool UseLoggingVariables() /// /// Log context. /// - [SuppressMessage( - "Performance", - "CA1822:Mark members as static", - Justification = "Issue with conditional compilation using UNIX symbol.")] - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { WriteEvent(id, channel, opcode, GetPSLevelFromSeverity(logContext.Severity), task, (PSKeyword)0x0, LogContextToString(logContext), GetPSLogUserData(logContext.ExecutionContext), payLoad); @@ -276,11 +268,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTas /// /// /// - [SuppressMessage( - "Performance", - "CA1822:Mark members as static", - Justification = "Issue with conditional compilation using UNIX symbol.")] - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) { long longKeyword = 0x00; @@ -303,11 +291,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev /// /// Writes an activity transfer event. /// - [SuppressMessage( - "Performance", - "CA1822:Mark members as static", - Justification = "Issue with conditional compilation using UNIX symbol.")] - internal void WriteTransferEvent(Guid parentActivityId) + internal static void WriteTransferEvent(Guid parentActivityId) { etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } @@ -315,11 +299,7 @@ internal void WriteTransferEvent(Guid parentActivityId) /// /// /// - [SuppressMessage( - "Performance", - "CA1822:Mark members as static", - Justification = "Issue with conditional compilation using UNIX symbol.")] - internal void SetActivityIdForCurrentThread(Guid newActivityId) + internal static void SetActivityIdForCurrentThread(Guid newActivityId) { Guid result = newActivityId; EventProvider.SetActivityId(ref result); diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index 011d7577239..4829a8ef5f6 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -71,7 +71,7 @@ private static StringBuilder PayloadBuilder /// may want to call this function if the provider needs to perform extra work to generate the event. In this case, /// calling this function first to determine if a session requested the event or not, may save resources and time. /// - internal bool IsEnabled(PSLevel level, PSKeyword keywords) + internal static bool IsEnabled(PSLevel level, PSKeyword keywords) { return s_provider.IsEnabled(level, keywords); } @@ -291,7 +291,7 @@ internal override bool UseLoggingVariables() /// /// Log context. /// - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { s_provider.Log(id, channel, task, opcode, GetPSLevelFromSeverity(logContext.Severity), DefaultKeywords, LogContextToString(logContext), @@ -309,7 +309,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTas /// /// /// - internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) + internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) { s_provider.Log(id, channel, task, opcode, level, keyword, args); } @@ -317,18 +317,18 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev /// /// Writes an activity transfer event. /// - internal void WriteTransferEvent(Guid parentActivityId) + internal static void WriteTransferEvent(Guid parentActivityId) { - s_provider.LogTransfer(parentActivityId); + SysLogProvider.LogTransfer(parentActivityId); } /// /// Sets the activity id for the current thread. /// /// The GUID identifying the activity. - internal void SetActivityIdForCurrentThread(Guid newActivityId) + internal static void SetActivityIdForCurrentThread(Guid newActivityId) { - s_provider.SetActivity(newActivityId); + SysLogProvider.SetActivity(newActivityId); } } } diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index 27d0e133fd5..6c822e1e0c5 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -290,7 +290,7 @@ private static void GetEventMessage(StringBuilder sb, PSEventId eventId, params /// Logs a activity transfer. /// /// The parent activity id. - public void LogTransfer(Guid parentActivityId) + public static void LogTransfer(Guid parentActivityId) { // NOTE: always log int threadId = Environment.CurrentManagedThreadId; @@ -307,7 +307,7 @@ public void LogTransfer(Guid parentActivityId) /// Logs the activity identifier for the current thread. /// /// The Guid activity identifier. - public void SetActivity(Guid activity) + public static void SetActivity(Guid activity) { int threadId = Environment.CurrentManagedThreadId; Activity = activity; From 13fe493286144b24b032373e305548ba4f152fd1 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 18:40:43 +0100 Subject: [PATCH 11/12] Fix IDE0059: Remove unnecessary value assignment --- .../engine/ManagementObjectAdapter.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 499702c67b3..7ac9f68528c 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1154,7 +1154,6 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri catch (Exception e) { // TODO: Bug 251457. This is a workaround to unblock partners and find out the root cause. - Tracing.PSEtwLogProvider provider = new Tracing.PSEtwLogProvider(); Tracing.PSEtwLogProvider.WriteEvent(PSEventId.Engine_Health, PSChannel.Analytic, From bbb82f3306791caf361e4081fb8bf73a6a20b1ef Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 29 Jul 2021 18:54:30 +0100 Subject: [PATCH 12/12] fixup! e141d56ea --- .../utils/tracing/PSEtwLog.cs | 32 +++++++++---------- .../utils/tracing/PSEtwLogProvider.cs | 30 ++++++++++++++--- 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index a2191fa64a1..ca8471749eb 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -140,7 +140,7 @@ internal static void LogSettingsEvent(LogContext logContext, string variableName /// internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -153,7 +153,7 @@ internal static void LogOperationalInformation(PSEventId id, PSOpcode opcode, PS /// internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -166,7 +166,7 @@ internal static void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -179,7 +179,7 @@ internal static void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask /// internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Error, task, keyword, args); } /// @@ -192,7 +192,7 @@ internal static void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task /// internal static void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Warning, task, keyword, args); } /// @@ -216,12 +216,12 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta UInt32 fragmentLength, PSETWBinaryBlob fragmentData) { - if (PSEtwLogProvider.IsEnabled(PSLevel.Verbose, keyword)) + if (provider.IsEnabled(PSLevel.Verbose, keyword)) { string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); payLoadData = string.Format(CultureInfo.InvariantCulture, "0x{0}", payLoadData.Replace("-", string.Empty)); - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, payLoadData); } @@ -237,7 +237,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, args); } /// @@ -250,7 +250,7 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta /// internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); + provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Informational, task, keyword, args); } /// @@ -263,7 +263,7 @@ internal static void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PST /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); + provider.WriteEvent(id, PSChannel.Operational, opcode, PSLevel.Error, task, keyword, args); } /// @@ -276,19 +276,19 @@ internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask t /// internal static void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { - PSEtwLogProvider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); + provider.WriteEvent(id, PSChannel.Operational, opcode, task, logContext, payLoad); } internal static void SetActivityIdForCurrentThread(Guid newActivityId) { - PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); + provider.SetActivityIdForCurrentThread(newActivityId); } internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { // set the new activity id - PSEtwLogProvider.SetActivityIdForCurrentThread(newActivityId); + provider.SetActivityIdForCurrentThread(newActivityId); // Once the activity id is set, write the transfer event WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); @@ -308,10 +308,10 @@ internal static void ReplaceActivityIdForCurrentThread(Guid newActivityId, internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - PSEtwLogProvider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, + provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysOperational); - PSEtwLogProvider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, + provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysAnalytic); } @@ -321,7 +321,7 @@ internal static void WriteTransferEvent(Guid relatedActivityId, PSEventId eventF /// internal static void WriteTransferEvent(Guid parentActivityId) { - PSEtwLogProvider.WriteTransferEvent(parentActivityId); + provider.WriteTransferEvent(parentActivityId); } } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 23834626f4b..5a6f72d3df7 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -40,7 +40,11 @@ static PSEtwLogProvider() /// may want to call this function if the provider needs to perform extra work to generate the event. In this case, /// calling this function first to determine if a session requested the event or not, may save resources and time. /// - internal static bool IsEnabled(PSLevel level, PSKeyword keywords) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal bool IsEnabled(PSLevel level, PSKeyword keywords) { return etwProvider.IsEnabled((byte)level, (long)keywords); } @@ -252,7 +256,11 @@ internal override bool UseLoggingVariables() /// /// Log context. /// - internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { WriteEvent(id, channel, opcode, GetPSLevelFromSeverity(logContext.Severity), task, (PSKeyword)0x0, LogContextToString(logContext), GetPSLogUserData(logContext.ExecutionContext), payLoad); @@ -268,7 +276,11 @@ internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode /// /// /// - internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLevel level, PSTask task, PSKeyword keyword, params object[] args) { long longKeyword = 0x00; @@ -291,7 +303,11 @@ internal static void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode /// /// Writes an activity transfer event. /// - internal static void WriteTransferEvent(Guid parentActivityId) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void WriteTransferEvent(Guid parentActivityId) { etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } @@ -299,7 +315,11 @@ internal static void WriteTransferEvent(Guid parentActivityId) /// /// /// - internal static void SetActivityIdForCurrentThread(Guid newActivityId) + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Issue with conditional compilation using UNIX symbol.")] + internal void SetActivityIdForCurrentThread(Guid newActivityId) { Guid result = newActivityId; EventProvider.SetActivityId(ref result);