From c780730a0db3d72f60b878b1cbc90977eaba0e45 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 7 Jul 2026 09:59:39 -0700 Subject: [PATCH 1/2] Remove unused .cs and .resx files --- .../CounterFileInfo.cs | 56 - .../ExportCounterCommand.cs | 383 - .../GetEventSnapin.cs | 109 - .../ImportCounterCommand.cs | 681 -- ...oft.PowerShell.Commands.Diagnostics.csproj | 7 - ...soft.PowerShell.Commands.Management.csproj | 31 - .../management/CommitTransactionCommand.cs | 30 - .../management/ControlPanelItemCommand.cs | 762 -- .../commands/management/Eventlog.cs | 1467 --- .../management/GetTransactionCommand.cs | 25 - .../management/GetWMIObjectCommand.cs | 440 - .../management/InvokeWMIMethodCommand.cs | 318 - .../management/RegisterWMIEventCommand.cs | 194 - .../management/RemoveWMIObjectCommand.cs | 183 - .../management/RollbackTransactionCommand.cs | 30 - .../management/SetWMIInstanceCommand.cs | 186 - .../management/StartTransactionCommand.cs | 109 - .../management/UseTransactionCommand.cs | 93 - .../commands/management/WMIHelper.cs | 2083 ---- .../commands/management/WebServiceProxy.cs | 494 - .../resources/ControlPanelResources.resx | 150 - .../resources/EventlogResources.resx | 180 - .../ManagementMshSnapInResources.resx | 129 - .../resources/TransactionResources.resx | 123 - .../resources/WebServiceResources.resx | 126 - .../resources/WmiResources.resx | 138 - .../installer/MshManagementMshSnapin.cs | 81 - ...crosoft.PowerShell.Commands.Utility.csproj | 15 - .../resources/ConvertFromStringResources.resx | 150 - .../resources/ConvertStringResources.resx | 129 - .../resources/FlashExtractStrings.resx | 213 - .../resources/ImmutableStrings.resx | 123 - .../resources/UtilityMshSnapinResources.resx | 129 - .../installer/MshUtilityMshSnapin.cs | 79 - .../Microsoft.PowerShell.ConsoleHost.csproj | 8 - .../resources/HostMshSnapinResources.resx | 129 - .../singleshell/installer/EngineInstaller.cs | 75 - .../singleshell/installer/MshHostMshSnapin.cs | 79 - .../Microsoft.PowerShell.Security.csproj | 7 - .../resources/SecurityMshSnapinResources.resx | 129 - .../installer/MshSecurityMshSnapin.cs | 88 - .../Microsoft.WSMan.Management.csproj | 4 - src/Microsoft.WSMan.Management/WsManSnapin.cs | 92 - .../System.Management.Automation.csproj | 24 +- ...mdlets-over-objects.objectModel.autogen.cs | 2239 ---- ...lets-over-objects.xmlSerializer.autogen.cs | 10110 ---------------- .../engine/TransactedString.cs | 197 - .../engine/TransactionManager.cs | 708 -- .../engine/hostifaces/RunspaceInvoke.cs | 163 - .../engine/remoting/commands/ResumeJob.cs | 300 - .../engine/remoting/commands/SuspendJob.cs | 394 - .../namespaces/SafeTransactionHandle.cs | 82 - .../namespaces/TransactedRegistry.cs | 121 - .../namespaces/TransactedRegistryKey.cs | 2057 ---- .../namespaces/TransactedRegistrySecurity.cs | 456 - .../resources/CoreMshSnapinResources.resx | 129 - .../resources/ErrorPackageRemoting.resx | 120 - .../utils/BackgroundDispatcher.cs | 133 - .../perfCounters/CounterSetInstanceBase.cs | 596 - .../perfCounters/CounterSetRegistrarBase.cs | 271 - .../utils/perfCounters/PSPerfCountersMgr.cs | 454 - 61 files changed, 1 insertion(+), 28610 deletions(-) delete mode 100644 src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs delete mode 100644 src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx delete mode 100644 src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs delete mode 100644 src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs delete mode 100644 src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx delete mode 100644 src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs delete mode 100644 src/Microsoft.WSMan.Management/WsManSnapin.cs delete mode 100644 src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs delete mode 100644 src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs delete mode 100644 src/System.Management.Automation/engine/TransactedString.cs delete mode 100644 src/System.Management.Automation/engine/TransactionManager.cs delete mode 100644 src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs delete mode 100644 src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs delete mode 100644 src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs delete mode 100644 src/System.Management.Automation/namespaces/SafeTransactionHandle.cs delete mode 100644 src/System.Management.Automation/namespaces/TransactedRegistry.cs delete mode 100644 src/System.Management.Automation/namespaces/TransactedRegistryKey.cs delete mode 100644 src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs delete mode 100644 src/System.Management.Automation/resources/CoreMshSnapinResources.resx delete mode 100644 src/System.Management.Automation/resources/ErrorPackageRemoting.resx delete mode 100644 src/System.Management.Automation/utils/BackgroundDispatcher.cs delete mode 100644 src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs delete mode 100644 src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs delete mode 100644 src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs deleted file mode 100644 index 2b11b6d3b03..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; - -namespace Microsoft.PowerShell.Commands.GetCounter -{ - public class CounterFileInfo - { - internal CounterFileInfo(DateTime oldestRecord, - DateTime newestRecord, - UInt32 sampleCount) - { - _oldestRecord = oldestRecord; - _newestRecord = newestRecord; - _sampleCount = sampleCount; - } - - internal CounterFileInfo() { } - - public DateTime OldestRecord - { - get - { - return _oldestRecord; - } - } - - private DateTime _oldestRecord = DateTime.MinValue; - - public DateTime NewestRecord - { - get - { - return _newestRecord; - } - } - - private DateTime _newestRecord = DateTime.MaxValue; - - public UInt32 SampleCount - { - get - { - return _sampleCount; - } - } - - private UInt32 _sampleCount = 0; - } -} diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs deleted file mode 100644 index 9385e55909f..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.IO; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Net; -using System.Reflection; -using System.Resources; -using System.Security; -using System.Security.Principal; -using System.Text; -using System.Threading; -using System.Xml; - -using Microsoft.PowerShell.Commands.Diagnostics.Common; -using Microsoft.PowerShell.Commands.GetCounter; -using Microsoft.Powershell.Commands.GetCounter.PdhNative; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Class that implements the Get-Counter cmdlet. - /// - [Cmdlet(VerbsData.Export, "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138337")] - public sealed class ExportCounterCommand : PSCmdlet - { - // - // Path parameter - // - [Parameter( - Mandatory = true, - Position = 0, - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources")] - [Alias("PSPath")] - - public string Path - { - get { return _path; } - - set { _path = value; } - } - - private string _path; - private string _resolvedPath; - - // - // Format parameter. - // Valid strings are "blg", "csv", "tsv" (case-insensitive). - // - [Parameter( - Mandatory = false, - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [ValidateNotNull] - [ValidateSet("blg", "csv", "tsv")] - public string FileFormat - { - get { return _format; } - - set { _format = value; } - } - - private string _format = "blg"; - - // - // MaxSize parameter - // Maximum output file size, in megabytes. - // - [Parameter( - HelpMessageBaseName = "GetEventResources")] - public UInt32 MaxSize - { - get { return _maxSize; } - - set { _maxSize = value; } - } - - private UInt32 _maxSize = 0; - - // - // InputObject parameter - // - [Parameter( - Mandatory = true, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources")] - - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.ExportCounterCommand.InputObject", - Justification = "A PerformanceCounterSampleSet[] is required here because Powershell supports arrays natively.")] - public PerformanceCounterSampleSet[] InputObject - { - get { return _counterSampleSets; } - - set { _counterSampleSets = value; } - } - - private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0]; - - // - // Force switch - // - [Parameter( - HelpMessageBaseName = "GetEventResources")] - public SwitchParameter Force - { - get { return _force; } - - set { _force = value; } - } - - private SwitchParameter _force; - - // - // Circular switch - // - [Parameter( - HelpMessageBaseName = "GetEventResources")] - public SwitchParameter Circular - { - get { return _circular; } - - set { _circular = value; } - } - - private SwitchParameter _circular; - - private ResourceManager _resourceMgr = null; - - private PdhHelper _pdhHelper = null; - - private bool _stopping = false; - - private bool _queryInitialized = false; - - private PdhLogFileType _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; - - // - // BeginProcessing() is invoked once per pipeline - // - protected override void BeginProcessing() - { - -#if CORECLR - if (Platform.IsIoT) - { - // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. - throw new PlatformNotSupportedException(); - } - - // PowerShell 7 requires at least Windows 7, - // so no version test is needed - _pdhHelper = new PdhHelper(false); -#else - // - // Determine the OS version: this cmdlet requires Windows 7 - // because it uses new Pdh functionality. - // - Version osVersion = System.Environment.OSVersion.Version; - if (osVersion.Major < 6 || - (osVersion.Major == 6 && osVersion.Minor < 1)) - { - string msg = _resourceMgr.GetString("ExportCtrWin7Required"); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); - } - - _pdhHelper = new PdhHelper(osVersion.Major < 6); -#endif - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - - // - // Set output format (log file type) - // - SetOutputFormat(); - - if (Circular.IsPresent && _maxSize == 0) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterCircularNoMaxSize")); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "CounterCircularNoMaxSize", ErrorCategory.InvalidResult, null)); - } - - uint res = _pdhHelper.ConnectToDataSource(); - if (res != 0) - { - ReportPdhError(res, true); - } - - res = _pdhHelper.OpenQuery(); - if (res != 0) - { - ReportPdhError(res, true); - } - } - - // - // EndProcessing() is invoked once per pipeline - // - protected override void EndProcessing() - { - _pdhHelper.Dispose(); - } - - /// - /// Handle Control-C - /// - protected override void StopProcessing() - { - _stopping = true; - _pdhHelper.Dispose(); - } - - // - // ProcessRecord() override. - // This is the main entry point for the cmdlet. - // When counter data comes from the pipeline, this gets invoked for each pipelined object. - // When it's passed in as an argument, ProcessRecord() is called once for the entire _counterSampleSets array. - // - protected override void ProcessRecord() - { - Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null); - - ResolvePath(); - - uint res = 0; - - if (!_queryInitialized) - { - if (_format.ToLowerInvariant().Equals("blg")) - { - res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]); - } - else - { - res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]); - } - - if (res != 0) - { - ReportPdhError(res, true); - } - - res = _pdhHelper.OpenLogForWriting(_resolvedPath, _outputFormat, Force.IsPresent, _maxSize * 1024 * 1024, Circular.IsPresent, null); - if (res == PdhResults.PDH_FILE_ALREADY_EXISTS) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterFileExists"), _resolvedPath); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterFileExists", ErrorCategory.InvalidResult, null)); - } - else if (res == PdhResults.PDH_LOG_FILE_CREATE_ERROR) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileCreateFailed"), _resolvedPath); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "FileCreateFailed", ErrorCategory.InvalidResult, null)); - } - else if (res == PdhResults.PDH_LOG_FILE_OPEN_ERROR) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileOpenFailed"), _resolvedPath); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "FileOpenFailed", ErrorCategory.InvalidResult, null)); - } - else if (res != 0) - { - ReportPdhError(res, true); - } - - _queryInitialized = true; - } - - foreach (PerformanceCounterSampleSet set in _counterSampleSets) - { - _pdhHelper.ResetRelogValues(); - - foreach (PerformanceCounterSample sample in set.CounterSamples) - { - bool bUnknownKey = false; - res = _pdhHelper.SetCounterValue(sample, out bUnknownKey); - if (bUnknownKey) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterExportSampleNotInInitialSet"), sample.Path, _resolvedPath); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "CounterExportSampleNotInInitialSet", ErrorCategory.InvalidResult, null)); - } - else if (res != 0) - { - ReportPdhError(res, true); - } - } - - res = _pdhHelper.WriteRelogSample(set.Timestamp); - if (res != 0) - { - ReportPdhError(res, true); - } - - if (_stopping) - { - break; - } - } - } - - // Determines Log File Type based on FileFormat parameter - // - private void SetOutputFormat() - { - switch (_format.ToLowerInvariant()) - { - case "csv": - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; - break; - case "tsv": - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; - break; - default: // By default file format is blg - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; - break; - } - } - - private void ResolvePath() - { - try - { - Collection result = null; - result = SessionState.Path.GetResolvedPSPathFromPSPath(_path); - if (result.Count > 1) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ExportDestPathAmbiguous"), _path); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "ExportDestPathAmbiguous", ErrorCategory.InvalidArgument, null)); - } - - foreach (PathInfo currentPath in result) - { - _resolvedPath = currentPath.ProviderPath; - } - } - catch (ItemNotFoundException pathNotFound) - { - // - // This is an expected condition - we will be creating a new file - // - _resolvedPath = pathNotFound.ItemName; - } - } - - private void ReportPdhError(uint res, bool bTerminate) - { - string msg; - uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); - if (formatRes != 0) - { - msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); - } - - Exception exc = new Exception(msg); - if (bTerminate) - { - ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - } - else - { - WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs deleted file mode 100644 index a4693c454c0..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Management.Automation; -using System.Text; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Create the PowerShell snap-in used to register the - /// Get-WinEvent cmdlet. Declaring the PSSnapIn class identifies - /// this .cs file as a PowerShell snap-in. - /// - [RunInstaller(true)] - public class GetEventPSSnapIn : PSSnapIn - { - /// - /// Create an instance of the GetEventPSSnapIn class. - /// - public GetEventPSSnapIn() - : base() - { - } - - /// - /// Specify the name of the PowerShell snap-in. - /// - public override string Name - { - get - { - return "Microsoft.Powershell.GetEvent"; - } - } - - /// - /// Specify the vendor of the PowerShell snap-in. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. - /// - public override string VendorResource - { - get - { - return "GetEventResources,Vendor"; - } - } - - /// - /// Specifies the description of the PowerShell snap-in. - /// - public override string Description - { - get - { - return "This PS snap-in contains Get-WinEvent cmdlet used to read Windows event log data and configuration."; - } - } - - /// - /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. - /// - public override string DescriptionResource - { - get - { - return "GetEventResources,Description"; - } - } - - /// - /// Get type files to be used for this PSSnapin. - /// - public override string[] Types - { - get - { - return _types; - } - } - - private string[] _types = new string[] { "getevent.types.ps1xml" }; - - /// - /// Get format files to be used for this PSSnapin. - /// - public override string[] Formats - { - get - { - return _formats; - } - } - - private string[] _formats = new string[] { "Event.format.ps1xml" }; - } -} diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs deleted file mode 100644 index 729334d0605..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ /dev/null @@ -1,681 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.IO; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Net; -using System.Reflection; -using System.Resources; -using System.Security; -using System.Security.Principal; -using System.Text; -using System.Threading; -using System.Xml; - -using Microsoft.PowerShell.Commands.Diagnostics.Common; -using Microsoft.PowerShell.Commands.GetCounter; -using Microsoft.Powershell.Commands.GetCounter.PdhNative; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Class that implements the Get-Counter cmdlet. - /// - [Cmdlet(VerbsData.Import, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138338")] - public sealed class ImportCounterCommand : PSCmdlet - { - // - // Path parameter - // - [Parameter( - Position = 0, - Mandatory = true, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources")] - [Alias("PSPath")] - - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", - Justification = "A string[] is required here because that is the type Powershell supports")] - public string[] Path - { - get { return _path; } - - set { _path = value; } - } - - private string[] _path; - - private StringCollection _resolvedPaths = new StringCollection(); - - private List _accumulatedFileNames = new List(); - - // - // ListSet parameter - // - [Parameter( - Mandatory = true, - ParameterSetName = "ListSetSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [AllowEmptyCollection] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", - Justification = "A string[] is required here because that is the type Powershell supports")] - public string[] ListSet - { - get { return _listSet; } - - set { _listSet = value; } - } - - private string[] _listSet = Array.Empty(); - - // - // StartTime parameter - // - [Parameter( - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - ParameterSetName = "GetCounterSet", - HelpMessageBaseName = "GetEventResources")] - public DateTime StartTime - { - get { return _startTime; } - - set { _startTime = value; } - } - - private DateTime _startTime = DateTime.MinValue; - - // - // EndTime parameter - // - [Parameter( - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - ParameterSetName = "GetCounterSet", - HelpMessageBaseName = "GetEventResources")] - public DateTime EndTime - { - get { return _endTime; } - - set { _endTime = value; } - } - - private DateTime _endTime = DateTime.MaxValue; - - // - // Counter parameter - // - [Parameter( - Mandatory = false, - ParameterSetName = "GetCounterSet", - ValueFromPipeline = false, - HelpMessageBaseName = "GetEventResources")] - [AllowEmptyCollection] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet", - Justification = "A string[] is required here because that is the type Powershell supports")] - public string[] Counter - { - get { return _counter; } - - set { _counter = value; } - } - - private string[] _counter = Array.Empty(); - - // - // Summary switch - // - [Parameter(ParameterSetName = "SummarySet")] - public SwitchParameter Summary - { - get { return _summary; } - - set { _summary = value; } - } - - private SwitchParameter _summary; - - // - // MaxSamples parameter - // - private const Int64 KEEP_ON_SAMPLING = -1; - [Parameter( - ParameterSetName = "GetCounterSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [ValidateRange((Int64)1, Int64.MaxValue)] - public Int64 MaxSamples - { - get { return _maxSamples; } - - set { _maxSamples = value; } - } - - private Int64 _maxSamples = KEEP_ON_SAMPLING; - - private ResourceManager _resourceMgr = null; - - private PdhHelper _pdhHelper = null; - - private bool _stopping = false; - - // - // AccumulatePipelineFileNames() accumulates counter file paths in the pipeline scenario: - // we do not want to construct a Pdh query until all the file names are supplied. - // - private void AccumulatePipelineFileNames() - { - _accumulatedFileNames.AddRange(_path); - } - - // - // BeginProcessing() is invoked once per pipeline - // - protected override void BeginProcessing() - { - -#if CORECLR - if (Platform.IsIoT) - { - // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. - throw new PlatformNotSupportedException(); - } - - // PowerShell 7 requires at least Windows 7, - // so no version test is needed - _pdhHelper = new PdhHelper(false); -#else - _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); -#endif - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - } - - // - // EndProcessing() is invoked once per pipeline - // - protected override void EndProcessing() - { - // - // Resolve and validate the Path argument: present for all parametersets. - // - if (!ResolveFilePaths()) - { - return; - } - - ValidateFilePaths(); - - switch (ParameterSetName) - { - case "ListSetSet": - ProcessListSet(); - break; - - case "GetCounterSet": - ProcessGetCounter(); - break; - - case "SummarySet": - ProcessSummary(); - break; - - default: - Debug.Assert(false, $"Invalid parameter set name: {ParameterSetName}"); - break; - } - - _pdhHelper.Dispose(); - } - - // - // Handle Control-C - // - protected override void StopProcessing() - { - _stopping = true; - _pdhHelper.Dispose(); - } - - // - // ProcessRecord() override. - // This is the main entry point for the cmdlet. - // - protected override void ProcessRecord() - { - AccumulatePipelineFileNames(); - } - - // - // ProcessSummary(). - // Does the work to process Summary parameter set. - // - private void ProcessSummary() - { - uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); - if (res != 0) - { - ReportPdhError(res, true); - return; - } - - CounterFileInfo summaryObj; - res = _pdhHelper.GetFilesSummary(out summaryObj); - - if (res != 0) - { - ReportPdhError(res, true); - return; - } - - WriteObject(summaryObj); - } - - // - // ProcessListSet(). - // Does the work to process ListSet parameter set. - // - private void ProcessListSet() - { - uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); - if (res != 0) - { - ReportPdhError(res, true); - return; - } - - StringCollection machineNames = new StringCollection(); - res = _pdhHelper.EnumBlgFilesMachines(ref machineNames); - if (res != 0) - { - ReportPdhError(res, true); - return; - } - - foreach (string machine in machineNames) - { - StringCollection counterSets = new StringCollection(); - res = _pdhHelper.EnumObjects(machine, ref counterSets); - if (res != 0) - { - return; - } - - StringCollection validPaths = new StringCollection(); - - foreach (string pattern in _listSet) - { - bool bMatched = false; - - WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); - - foreach (string counterSet in counterSets) - { - if (!wildLogPattern.IsMatch(counterSet)) - { - continue; - } - - StringCollection counterSetCounters = new StringCollection(); - StringCollection counterSetInstances = new StringCollection(); - - res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); - if (res != 0) - { - ReportPdhError(res, false); - continue; - } - - string[] instanceArray = new string[counterSetInstances.Count]; - int i = 0; - foreach (string instance in counterSetInstances) - { - instanceArray[i++] = instance; - } - - Dictionary counterInstanceMapping = new Dictionary(); - foreach (string counter in counterSetCounters) - { - counterInstanceMapping.Add(counter, instanceArray); - } - - PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; - if (counterSetInstances.Count > 1) - { - categoryType = PerformanceCounterCategoryType.MultiInstance; - } - else // if (counterSetInstances.Count == 1) //??? - { - categoryType = PerformanceCounterCategoryType.SingleInstance; - } - - string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet); - - CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping); - WriteObject(setObj); - bMatched = true; - } - - if (!bMatched) - { - string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, - CommonUtilities.StringArrayToString(_resolvedPaths), - pattern)); - WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null)); - } - } - } - } - - // - // ProcessGetCounter() - // Does the work to process GetCounterSet parameter set. - // - private void ProcessGetCounter() - { - // Validate StartTime-EndTime, if present - if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) - { - if (_startTime >= _endTime) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidDateRange")); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidDateRange", ErrorCategory.InvalidArgument, null)); - return; - } - } - - uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths); - if (res != 0) - { - ReportPdhError(res, true); - return; - } - - StringCollection validPaths = new StringCollection(); - if (_counter.Length > 0) - { - foreach (string path in _counter) - { - StringCollection expandedPaths; - res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths); - if (res != 0) - { - WriteDebug(path); - ReportPdhError(res, false); - continue; - } - - foreach (string expandedPath in expandedPaths) - { - if (!_pdhHelper.IsPathValid(expandedPath)) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathIsInvalid"), path); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); - - continue; - } - - validPaths.Add(expandedPath); - } - } - - if (validPaths.Count == 0) - { - return; - } - } - else - { - res = _pdhHelper.GetValidPathsFromFiles(ref validPaths); - if (res != 0) - { - ReportPdhError(res, false); - } - } - - if (validPaths.Count == 0) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid")); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null)); - } - - res = _pdhHelper.OpenQuery(); - if (res != 0) - { - ReportPdhError(res, false); - } - - if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) - { - res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime); - if (res != 0) - { - ReportPdhError(res, true); - } - } - - res = _pdhHelper.AddCounters(ref validPaths, true); - if (res != 0) - { - ReportPdhError(res, true); - } - - PerformanceCounterSampleSet nextSet; - - uint samplesRead = 0; - - while (!_stopping) - { - res = _pdhHelper.ReadNextSet(out nextSet, false); - if (res == PdhResults.PDH_NO_MORE_DATA) - { - break; - } - - if (res != 0 && res != PdhResults.PDH_INVALID_DATA) - { - ReportPdhError(res, false); - continue; - } - - // - // Display data - // - WriteSampleSetObject(nextSet, (samplesRead == 0)); - - samplesRead++; - - if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples) - { - break; - } - } - } - - // - // ValidateFilePaths() helper. - // Validates the _resolvedPaths: present for all parametersets. - // We cannot have more than 32 blg files, or more than one CSV or TSC file. - // Files have to all be of the same type (.blg, .csv, .tsv). - // - private void ValidateFilePaths() - { - Debug.Assert(_resolvedPaths.Count > 0); - - string firstExt = System.IO.Path.GetExtension(_resolvedPaths[0]); - foreach (string fileName in _resolvedPaths) - { - WriteVerbose(fileName); - string curExtension = System.IO.Path.GetExtension(fileName); - - if (!curExtension.Equals(".blg", StringComparison.OrdinalIgnoreCase) - && !curExtension.Equals(".csv", StringComparison.OrdinalIgnoreCase) - && !curExtension.Equals(".tsv", StringComparison.OrdinalIgnoreCase)) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNotALogFile"), fileName); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterNotALogFile", ErrorCategory.InvalidResult, null)); - return; - } - - if (!curExtension.Equals(firstExt, StringComparison.OrdinalIgnoreCase)) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNoMixedLogTypes"), fileName); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterNoMixedLogTypes", ErrorCategory.InvalidResult, null)); - return; - } - } - - if (firstExt.Equals(".blg", StringComparison.OrdinalIgnoreCase)) - { - if (_resolvedPaths.Count > 32) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter32FileLimit")); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "Counter32FileLimit", ErrorCategory.InvalidResult, null)); - return; - } - } - else if (_resolvedPaths.Count > 1) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter1FileLimit")); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "Counter1FileLimit", ErrorCategory.InvalidResult, null)); - return; - } - } - - // - // ResolveFilePath helper. - // Returns a string collection of resolved file paths. - // Writes non-terminating errors for invalid paths - // and returns an empty collection. - // - private bool ResolveFilePaths() - { - StringCollection retColl = new StringCollection(); - - foreach (string origPath in _accumulatedFileNames) - { - Collection resolvedPathSubset = null; - try - { - resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(origPath); - } - catch (PSNotSupportedException notSupported) - { - WriteError(new ErrorRecord(notSupported, string.Empty, ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (System.Management.Automation.DriveNotFoundException driveNotFound) - { - WriteError(new ErrorRecord(driveNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (ProviderNotFoundException providerNotFound) - { - WriteError(new ErrorRecord(providerNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (ItemNotFoundException pathNotFound) - { - WriteError(new ErrorRecord(pathNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, string.Empty, ErrorCategory.ObjectNotFound, origPath)); - continue; - } - - foreach (PathInfo pi in resolvedPathSubset) - { - // - // Check the provider: only FileSystem provider paths are acceptable. - // - if (pi.Provider.Name != "FileSystem") - { - string msg = _resourceMgr.GetString("NotAFileSystemPath"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, origPath)); - WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, origPath)); - continue; - } - - _resolvedPaths.Add(pi.ProviderPath.ToLowerInvariant()); - } - } - - return (_resolvedPaths.Count > 0); - } - - private void ReportPdhError(uint res, bool bTerminate) - { - string msg; - uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); - if (formatRes != 0) - { - msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); - } - - Exception exc = new Exception(msg); - if (bTerminate) - { - ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - } - else - { - WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - } - } - - // - // WriteSampleSetObject() helper. - // In addition to writing the PerformanceCounterSampleSet object, - // it writes a single error if one of the samples has an invalid (non-zero) status. - // The only exception is the first set, where we allow for the formatted value to be 0 - - // this is expected for CSV and TSV files. - - private void WriteSampleSetObject(PerformanceCounterSampleSet set, bool firstSet) - { - if (!firstSet) - { - foreach (PerformanceCounterSample sample in set.CounterSamples) - { - if (sample.Status != 0) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid")); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - break; - } - } - } - - WriteObject(set); - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 94b090d4e02..7af6985f5a9 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -15,13 +15,6 @@ $(DefineConstants);CORECLR - - - - - - - diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 434322304e4..490854eb4b5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -14,37 +14,6 @@ $(DefineConstants);CORECLR - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs deleted file mode 100644 index 94e923bfa6e..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Management.Automation; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command that commits a transaction. - /// - [Cmdlet(VerbsLifecycle.Complete, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135200")] - public class CompleteTransactionCommand : PSCmdlet - { - /// - /// Commits the current transaction. - /// - protected override void EndProcessing() - { - // Commit the transaction - if (ShouldProcess( - NavigationResources.TransactionResource, - NavigationResources.CommitAction)) - { - this.Context.TransactionManager.Commit(); - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs deleted file mode 100644 index 3734eb82b0c..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ /dev/null @@ -1,762 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Management.Automation; -using System.Management.Automation.Internal; - -using Microsoft.Win32; - -using Dbg = System.Management.Automation.Diagnostics; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Represent a control panel item. - /// - public sealed class ControlPanelItem - { - /// - /// Control panel applet name. - /// - public string Name { get; } - - /// - /// Control panel applet canonical name. - /// - public string CanonicalName { get; } - - /// - /// Control panel applet category. - /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Category { get; } - - /// - /// Control panel applet description. - /// - public string Description { get; } - - /// - /// Control panel applet path. - /// - internal string Path { get; } - - /// - /// Internal constructor for ControlPanelItem. - /// - /// - /// - /// - /// - /// - internal ControlPanelItem(string name, string canonicalName, string[] category, string description, string path) - { - Name = name; - Path = path; - CanonicalName = canonicalName; - Category = category; - Description = description; - } - - /// - /// ToString method. - /// - /// - public override string ToString() - { - return this.Name; - } - } - - /// - /// This class implements the base for ControlPanelItem commands. - /// - public abstract class ControlPanelItemBaseCommand : PSCmdlet - { - /// - /// Locale specific verb action Open string exposed by the control panel item. - /// - private static string s_verbActionOpenName = null; - - /// - /// Canonical name of the control panel item used as a reference to fetch the verb - /// action Open string. This control panel item exists on all SKU's. - /// - private const string RegionCanonicalName = "Microsoft.RegionAndLanguage"; - - private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}"; - private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" }; - private const string TestHeadlessServerScript = @" -$result = $false -$serverManagerModule = Get-Module -ListAvailable | Where-Object {$_.Name -eq 'ServerManager'} -if ($serverManagerModule -ne $null) -{ - Import-Module ServerManager - $Gui = (Get-WindowsFeature Server-Gui-Shell).Installed - if ($Gui -eq $false) - { - $result = $true - } -} -$result -"; - internal readonly Dictionary CategoryMap = new Dictionary(StringComparer.OrdinalIgnoreCase); - - internal string[] CategoryNames = { "*" }; - internal string[] RegularNames = { "*" }; - internal string[] CanonicalNames = { "*" }; - internal ControlPanelItem[] ControlPanelItems = new ControlPanelItem[0]; - - /// - /// Get all executable control panel items. - /// - internal List AllControlPanelItems - { - get - { - if (_allControlPanelItems == null) - { - _allControlPanelItems = new List(); - string allItemFolderPath = ControlPanelShellFolder + "\\0"; - IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); - Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath); - FolderItems3 allItems = (FolderItems3)allItemFolder.Items(); - - bool applyControlPanelItemFilterList = IsServerCoreOrHeadLessServer(); - - foreach (ShellFolderItem item in allItems) - { - if (applyControlPanelItemFilterList) - { - bool match = false; - foreach (string name in s_controlPanelItemFilterList) - { - if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)) - { - match = true; - break; - } - } - - if (match) - continue; - } - - if (ContainVerbOpen(item)) - _allControlPanelItems.Add(item); - } - } - - return _allControlPanelItems; - } - } - - private List _allControlPanelItems; - - #region Cmdlet Overrides - - /// - /// Does the preprocessing for ControlPanelItem cmdlets. - /// - protected override void BeginProcessing() - { - System.OperatingSystem osInfo = System.Environment.OSVersion; - PlatformID platform = osInfo.Platform; - Version version = osInfo.Version; - - if (platform.Equals(PlatformID.Win32NT) && - ((version.Major < 6) || - ((version.Major == 6) && (version.Minor < 2)) - )) - { - // Below Win8, this cmdlet is not supported because of Win8:794135 - // throw terminating - string message = string.Format(CultureInfo.InvariantCulture, - ControlPanelResources.ControlPanelItemCmdletNotSupported, - this.CommandInfo.Name); - throw new PSNotSupportedException(message); - } - } - - #endregion - - /// - /// Test if an item can be invoked. - /// - /// - /// - private bool ContainVerbOpen(ShellFolderItem item) - { - bool result = false; - FolderItemVerbs verbs = item.Verbs(); - foreach (FolderItemVerb verb in verbs) - { - if (!string.IsNullOrEmpty(verb.Name) && - (verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) || - CompareVerbActionOpen(verb.Name))) - { - result = true; - break; - } - } - - return result; - } - - /// - /// CompareVerbActionOpen is a helper function used to perform locale specific - /// comparison of the verb action Open exposed by various control panel items. - /// - /// Locale specific verb action exposed by the control panel item. - /// True if the control panel item supports verb action open or else returns false. - private static bool CompareVerbActionOpen(string verbActionName) - { - if (s_verbActionOpenName == null) - { - const string allItemFolderPath = ControlPanelShellFolder + "\\0"; - IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); - Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath); - FolderItems3 allItems = (FolderItems3)allItemFolder.Items(); - - foreach (ShellFolderItem item in allItems) - { - string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); - canonicalName = !string.IsNullOrEmpty(canonicalName) - ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) - : null; - - if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase)) - { - // The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name - s_verbActionOpenName = item.Verbs().Item(0).Name; - break; - } - } - - Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always " - + "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point"); - } - - return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase); - } - - /// - /// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a - /// Server Core machine or if the Server-GUI-Shell feature is removed on the machine. - /// - /// True if the current SKU is a Server Core machine or if the Server-GUI-Shell - /// feature is removed on the machine or else returns false. - private bool IsServerCoreOrHeadLessServer() - { - bool result = false; - - using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")) - { - Dbg.Assert(installation != null, "the CurrentVersion subkey should exist"); - - string installationType = (string)installation.GetValue("InstallationType", string.Empty); - - if (installationType.Equals("Server Core")) - { - result = true; - } - else if (installationType.Equals("Server")) - { - using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) - { - ps.AddScript(TestHeadlessServerScript); - Collection psObjectCollection = ps.Invoke(Array.Empty()); - Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item"); - if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0]))) - { - result = true; - } - } - } - } - - return result; - } - - /// - /// Get the category number and name map. - /// - internal void GetCategoryMap() - { - if (CategoryMap.Count != 0) - { - return; - } - - IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); - Folder2 categoryFolder = (Folder2)shell2.NameSpace(ControlPanelShellFolder); - FolderItems3 catItems = (FolderItems3)categoryFolder.Items(); - - foreach (ShellFolderItem category in catItems) - { - string path = category.Path; - string catNum = path.Substring(path.LastIndexOf('\\') + 1); - - CategoryMap.Add(catNum, category.Name); - } - } - - /// - /// Get control panel item by the category. - /// - /// - /// - internal List GetControlPanelItemByCategory(List controlPanelItems) - { - List list = new List(); - HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); - - foreach (string pattern in CategoryNames) - { - bool found = false; - WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - foreach (ShellFolderItem item in controlPanelItems) - { - string path = item.Path; - int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category"); - foreach (int cat in categories) - { - string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof(string), CultureInfo.InvariantCulture); - Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in _categoryMap"); - string catName = CategoryMap[catStr]; - - if (!wildcard.IsMatch(catName)) - continue; - if (itemSet.Contains(path)) - { - found = true; - break; - } - - found = true; - itemSet.Add(path); - list.Add(item); - break; - } - } - - if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) - { - string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenCategory, pattern); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), - "NoControlPanelItemFoundForGivenCategory", - ErrorCategory.InvalidArgument, pattern); - WriteError(error); - } - } - - return list; - } - - /// - /// Get control panel item by the regular name. - /// - /// - /// - /// - internal List GetControlPanelItemByName(List controlPanelItems, bool withCategoryFilter) - { - List list = new List(); - HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); - - foreach (string pattern in RegularNames) - { - bool found = false; - WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - foreach (ShellFolderItem item in controlPanelItems) - { - string name = item.Name; - string path = item.Path; - if (!wildcard.IsMatch(name)) - continue; - if (itemSet.Contains(path)) - { - found = true; - continue; - } - - found = true; - itemSet.Add(path); - list.Add(item); - } - - if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) - { - string formatString = withCategoryFilter - ? ControlPanelResources.NoControlPanelItemFoundForGivenNameWithCategory - : ControlPanelResources.NoControlPanelItemFoundForGivenName; - string errMsg = StringUtil.Format(formatString, pattern); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), - "NoControlPanelItemFoundForGivenName", - ErrorCategory.InvalidArgument, pattern); - WriteError(error); - } - } - - return list; - } - - /// - /// Get control panel item by the canonical name. - /// - /// - /// - /// - internal List GetControlPanelItemByCanonicalName(List controlPanelItems, bool withCategoryFilter) - { - List list = new List(); - HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); - - if (CanonicalNames == null) - { - bool found = false; - foreach (ShellFolderItem item in controlPanelItems) - { - string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); - if (canonicalName == null) - { - found = true; - list.Add(item); - } - } - - if (!found) - { - string errMsg = withCategoryFilter - ? ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalNameWithCategory - : ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalName; - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), string.Empty, - ErrorCategory.InvalidArgument, CanonicalNames); - WriteError(error); - } - - return list; - } - - foreach (string pattern in CanonicalNames) - { - bool found = false; - WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - foreach (ShellFolderItem item in controlPanelItems) - { - string path = item.Path; - string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); - canonicalName = canonicalName != null - ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) - : null; - - if (canonicalName == null) - { - if (pattern.Equals("*", StringComparison.OrdinalIgnoreCase)) - { - found = true; - if (!itemSet.Contains(path)) - { - itemSet.Add(path); - list.Add(item); - } - } - } - else - { - if (!wildcard.IsMatch(canonicalName)) - continue; - if (itemSet.Contains(path)) - { - found = true; - continue; - } - - found = true; - itemSet.Add(path); - list.Add(item); - } - } - - if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern)) - { - string formatString = withCategoryFilter - ? ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalNameWithCategory - : ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalName; - string errMsg = StringUtil.Format(formatString, pattern); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), - "NoControlPanelItemFoundForGivenCanonicalName", - ErrorCategory.InvalidArgument, pattern); - WriteError(error); - } - } - - return list; - } - - /// - /// Get control panel item by the ControlPanelItem instances. - /// - /// - /// - internal List GetControlPanelItemsByInstance(List controlPanelItems) - { - List list = new List(); - HashSet itemSet = new HashSet(StringComparer.OrdinalIgnoreCase); - - foreach (ControlPanelItem controlPanelItem in ControlPanelItems) - { - bool found = false; - - foreach (ShellFolderItem item in controlPanelItems) - { - string path = item.Path; - if (!controlPanelItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase)) - continue; - if (itemSet.Contains(path)) - { - found = true; - break; - } - - found = true; - itemSet.Add(path); - list.Add(item); - break; - } - - if (!found) - { - string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenInstance, - controlPanelItem.GetType().Name); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), - "NoControlPanelItemFoundForGivenInstance", - ErrorCategory.InvalidArgument, controlPanelItem); - WriteError(error); - } - } - - return list; - } - } - - /// - /// Get all control panel items that is available in the "All Control Panel Items" category. - /// - [Cmdlet(VerbsCommon.Get, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219982")] - [OutputType(typeof(ControlPanelItem))] - public sealed class GetControlPanelItemCommand : ControlPanelItemBaseCommand - { - private const string RegularNameParameterSet = "RegularName"; - private const string CanonicalNameParameterSet = "CanonicalName"; - - #region "Parameters" - - /// - /// Control panel item names. - /// - [Parameter(Position = 0, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return RegularNames; } - - set - { - RegularNames = value; - _nameSpecified = true; - } - } - - private bool _nameSpecified = false; - - /// - /// Canonical names of control panel items. - /// - [Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)] - [AllowNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] CanonicalName - { - get { return CanonicalNames; } - - set - { - CanonicalNames = value; - _canonicalNameSpecified = true; - } - } - - private bool _canonicalNameSpecified = false; - - /// - /// Category of control panel items. - /// - [Parameter] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Category - { - get { return CategoryNames; } - - set - { - CategoryNames = value; - _categorySpecified = true; - } - } - - private bool _categorySpecified = false; - - #endregion "Parameters" - - /// - /// - protected override void ProcessRecord() - { - GetCategoryMap(); - List items = GetControlPanelItemByCategory(AllControlPanelItems); - - if (_nameSpecified) - { - items = GetControlPanelItemByName(items, _categorySpecified); - } - else if (_canonicalNameSpecified) - { - items = GetControlPanelItemByCanonicalName(items, _categorySpecified); - } - - List results = new List(); - foreach (ShellFolderItem item in items) - { - string name = item.Name; - string path = item.Path; - string description = (string)item.ExtendedProperty("InfoTip"); - string canonicalName = (string)item.ExtendedProperty("System.ApplicationName"); - canonicalName = canonicalName != null - ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) - : null; - int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category"); - string[] cateStrings = new string[categories.Length]; - for (int i = 0; i < categories.Length; i++) - { - string catStr = (string)LanguagePrimitives.ConvertTo(categories[i], typeof(string), CultureInfo.InvariantCulture); - Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in CategoryMap"); - cateStrings[i] = CategoryMap[catStr]; - } - - ControlPanelItem controlPanelItem = new ControlPanelItem(name, canonicalName, cateStrings, description, path); - results.Add(controlPanelItem); - } - - // Sort the results by Canonical Name - results.Sort(CompareControlPanelItems); - foreach (ControlPanelItem controlPanelItem in results) - { - WriteObject(controlPanelItem); - } - } - - #region "Private Methods" - - private static int CompareControlPanelItems(ControlPanelItem x, ControlPanelItem y) - { - // In the case that at least one of them is null - if (x.CanonicalName == null && y.CanonicalName == null) - return 0; - if (x.CanonicalName == null) - return 1; - if (y.CanonicalName == null) - return -1; - - // In the case that both are not null - return string.Compare(x.CanonicalName, y.CanonicalName, StringComparison.OrdinalIgnoreCase); - } - - #endregion "Private Methods" - } - - /// - /// Show the specified control panel applet. - /// - [Cmdlet(VerbsCommon.Show, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219983")] - public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand - { - private const string RegularNameParameterSet = "RegularName"; - private const string CanonicalNameParameterSet = "CanonicalName"; - private const string ControlPanelItemParameterSet = "ControlPanelItem"; - - #region "Parameters" - - /// - /// Control panel item names. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return RegularNames; } - - set { RegularNames = value; } - } - - /// - /// Canonical names of control panel items. - /// - [Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)] - [AllowNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] CanonicalName - { - get { return CanonicalNames; } - - set { CanonicalNames = value; } - } - - /// - /// Control panel items returned by Get-ControlPanelItem. - /// - [Parameter(Position = 0, ParameterSetName = ControlPanelItemParameterSet, ValueFromPipeline = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ControlPanelItem[] InputObject - { - get { return ControlPanelItems; } - - set { ControlPanelItems = value; } - } - - #endregion "Parameters" - - /// - /// - protected override void ProcessRecord() - { - List items; - if (ParameterSetName == RegularNameParameterSet) - { - items = GetControlPanelItemByName(AllControlPanelItems, false); - } - else if (ParameterSetName == CanonicalNameParameterSet) - { - items = GetControlPanelItemByCanonicalName(AllControlPanelItems, false); - } - else - { - items = GetControlPanelItemsByInstance(AllControlPanelItems); - } - - foreach (ShellFolderItem item in items) - { - item.InvokeVerb(); - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs deleted file mode 100644 index c667116fdd0..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ /dev/null @@ -1,1467 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; // Win32Exception -using System.Diagnostics; // Eventlog class -using System.Diagnostics.CodeAnalysis; -using System.Management.Automation; -using System.Management.Automation.Internal; - -namespace Microsoft.PowerShell.Commands -{ - #region GetEventLogCommand - /// - /// This class implements the Get-EventLog command. - /// - /// - /// The CLR EventLogEntryCollection class has problems with managing - /// rapidly spinning logs (i.e. logs set to "Overwrite" which are - /// rapidly getting new events and discarding old events). - /// In particular, if you enumerate forward - /// EventLogEntryCollection entries = log.Entries; - /// foreach (EventLogEntry entry in entries) - /// it will occasionally skip an entry. Conversely, if you are - /// enumerating backward - /// EventLogEntryCollection entries = log.Entries; - /// int count = entries.Count; - /// for (int i = count-1; i >= 0; i--) { - /// EventLogEntry entry = entries[i]; - /// it will occasionally repeat an entry. Accordingly, we enumerate - /// backward and try to leave off the repeated entries. - /// - [Cmdlet(VerbsCommon.Get, "EventLog", DefaultParameterSetName = "LogName", - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113314", RemotingCapability = RemotingCapability.SupportedByCommand)] - [OutputType(typeof(EventLog), typeof(EventLogEntry), typeof(string))] - public sealed class GetEventLogCommand : PSCmdlet - { - #region Parameters - /// - /// Read eventlog entries from this log. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "LogName")] - [Alias("LN")] - public string LogName { get; set; } - - /// - /// Read eventlog entries from this computer. - /// - [Parameter] - [ValidateNotNullOrEmpty] - [Alias("Cn")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName { get; set; } = Array.Empty(); - - /// - /// Read only this number of entries. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateRange(0, Int32.MaxValue)] - public int Newest { get; set; } = Int32.MaxValue; - - /// - /// Return entries "after " this date. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - public DateTime After - { - get { return _after; } - - set - { - _after = value; - _isDateSpecified = true; - _isFilterSpecified = true; - } - } - - private DateTime _after; - - /// - /// Return entries "Before" this date. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - public DateTime Before - { - get { return _before; } - - set - { - _before = value; - _isDateSpecified = true; - _isFilterSpecified = true; - } - } - - private DateTime _before; - - /// - /// Return entries for this user.Wild characters is supported. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] UserName - { - get { return _username; } - - set - { - _username = value; - _isFilterSpecified = true; - } - } - - private string[] _username; - - /// - /// Match eventlog entries by the InstanceIds - /// gets or sets an array of instanceIds. - /// - [Parameter(Position = 1, ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [ValidateRangeAttribute((long)0, long.MaxValue)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public long[] InstanceId - { - get { return _instanceIds; } - - set - { - _instanceIds = value; - _isFilterSpecified = true; - } - } - - private long[] _instanceIds = null; - - /// - /// Match eventlog entries by the Index - /// gets or sets an array of indexes. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [ValidateRangeAttribute((int)1, int.MaxValue)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public int[] Index - { - get { return _indexes; } - - set - { - _indexes = value; - _isFilterSpecified = true; - } - } - - private int[] _indexes = null; - - /// - /// Match eventlog entries by the EntryType - /// gets or sets an array of EntryTypes. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [Alias("ET")] - public string[] EntryType - { - get { return _entryTypes; } - - set - { - _entryTypes = value; - _isFilterSpecified = true; - } - } - - private string[] _entryTypes = null; - - /// - /// Get or sets an array of Source. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [Alias("ABO")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Source - { - get - { return _sources; } - - set - { - _sources = value; - _isFilterSpecified = true; - } - } - - private string[] _sources; - - /// - /// Get or Set Message string to searched in EventLog. - /// - [Parameter(ParameterSetName = "LogName")] - [ValidateNotNullOrEmpty] - [Alias("MSG")] - public string Message - { - get - { - return _message; - } - - set - { - _message = value; - _isFilterSpecified = true; - } - } - - private string _message; - - /// - /// Returns Log Entry as base object. - /// - [Parameter(ParameterSetName = "LogName")] - public SwitchParameter AsBaseObject { get; set; } - - /// - /// Return the Eventlog objects rather than the log contents. - /// - [Parameter(ParameterSetName = "List")] - public SwitchParameter List { get; set; } - - /// - /// Return the log names rather than the EventLog objects. - /// - [Parameter(ParameterSetName = "List")] - public SwitchParameter AsString - { - get - { - return _asString; - } - - set - { - _asString = value; - } - } - - private bool _asString /* = false */; - #endregion Parameters - - #region Overrides - - /// - /// Sets true when Filter is Specified. - /// - private bool _isFilterSpecified = false; - private bool _isDateSpecified = false; - private bool _isThrowError = true; - - /// - /// Process the specified logs. - /// - protected override void BeginProcessing() - { - if (ParameterSetName == "List") - { - if (ComputerName.Length > 0) - { - foreach (string computerName in ComputerName) - { - foreach (EventLog log in EventLog.GetEventLogs(computerName)) - { - if (AsString) - WriteObject(log.Log); - else - WriteObject(log); - } - } - } - else - { - foreach (EventLog log in EventLog.GetEventLogs()) - { - if (AsString) - WriteObject(log.Log); - else - WriteObject(log); - } - } - } - else - { - Diagnostics.Assert(ParameterSetName == "LogName", "Unexpected parameter set"); - - if (!WildcardPattern.ContainsWildcardCharacters(LogName)) - { - OutputEvents(LogName); - } - else - { - // - // If we were given a wildcard that matches more than one log, output the matching logs. Otherwise output the events in the matching log. - // - List matchingLogs = GetMatchingLogs(LogName); - - if (matchingLogs.Count == 1) - { - OutputEvents(matchingLogs[0].Log); - } - else - { - foreach (EventLog log in matchingLogs) - { - WriteObject(log); - } - } - } - } - } - #endregion Overrides - - #region Private - - private void OutputEvents(string logName) - { - // 2005/04/21-JonN This somewhat odd structure works - // around the FXCOP DisposeObjectsBeforeLosingScope rule. - bool processing = false; - try - { - if (ComputerName.Length == 0) - { - using (EventLog specificLog = new EventLog(logName)) - { - processing = true; - Process(specificLog); - } - } - else - { - processing = true; - - foreach (string computerName in ComputerName) - { - using (EventLog specificLog = new EventLog(logName, computerName)) - { - Process(specificLog); - } - } - } - } - catch (InvalidOperationException e) - { - if (processing) - { - throw; - } - - ThrowTerminatingError(new ErrorRecord( - e, // default exception text is OK - "EventLogNotFound", - ErrorCategory.ObjectNotFound, - logName)); - } - } - - private void Process(EventLog log) - { - bool matchesfound = false; - if (Newest == 0) - { - return; - } - - // enumerate backward, skipping repeat entries - EventLogEntryCollection entries = log.Entries; - - int count = entries.Count; - int lastindex = Int32.MinValue; - int processed = 0; - - for (int i = count - 1; (i >= 0) && (processed < Newest); i--) - { - EventLogEntry entry = null; - try - { - entry = entries[i]; - } - catch (ArgumentException e) - { - ErrorRecord er = new ErrorRecord( - e, - "LogReadError", - ErrorCategory.ReadError, - null - ); - er.ErrorDetails = new ErrorDetails( - this, - "EventlogResources", - "LogReadError", - log.Log, - e.Message - ); - WriteError(er); - - // NTRAID#Windows Out Of Band Releases-2005/09/27-JonN - // Break after the first one, rather than repeating this - // over and over - break; - } - catch (Exception e) - { - Diagnostics.Assert(false, - "EventLogEntryCollection error " - + e.GetType().FullName - + ": " + e.Message); - throw; - } - - if ((entry != null) && - ((lastindex == Int32.MinValue - || lastindex - entry.Index == 1))) - { - lastindex = entry.Index; - if (_isFilterSpecified) - { - if (!FiltersMatch(entry)) - continue; - } - - if (!AsBaseObject) - { - // wrapping in PSobject to insert into PStypesnames - PSObject logentry = new PSObject(entry); - // inserting at zero position in reverse order - logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source); - logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source + "/" + entry.InstanceId); - WriteObject(logentry); - matchesfound = true; - } - else - { - WriteObject(entry); - matchesfound = true; - } - - processed++; - } - } - - if (!matchesfound && _isThrowError) - { - Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, string.Empty)); - WriteError(new ErrorRecord(Ex, "GetEventLogNoEntriesFound", ErrorCategory.ObjectNotFound, null)); - } - } - - private bool FiltersMatch(EventLogEntry entry) - { - if (_indexes != null) - { - if (!((IList)_indexes).Contains(entry.Index)) - { - return false; - } - } - - if (_instanceIds != null) - { - if (!((IList)_instanceIds).Contains(entry.InstanceId)) - { - return false; - } - } - - if (_entryTypes != null) - { - bool entrymatch = false; - foreach (string type in _entryTypes) - { - if (type.Equals(entry.EntryType.ToString(), StringComparison.OrdinalIgnoreCase)) - { - entrymatch = true; - break; - } - } - - if (!entrymatch) - { - return entrymatch; - } - } - - if (_sources != null) - { - bool sourcematch = false; - foreach (string source in _sources) - { - if (WildcardPattern.ContainsWildcardCharacters(source)) - { - _isThrowError = false; - } - - WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase); - if (wildcardpattern.IsMatch(entry.Source)) - { - sourcematch = true; - break; - } - } - - if (!sourcematch) - { - return sourcematch; - } - } - - if (_message != null) - { - if (WildcardPattern.ContainsWildcardCharacters(_message)) - { - _isThrowError = false; - } - - WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase); - if (!wildcardpattern.IsMatch(entry.Message)) - { - return false; - } - } - - if (_username != null) - { - bool usernamematch = false; - foreach (string user in _username) - { - _isThrowError = false; - if (entry.UserName != null) - { - WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase); - if (wildcardpattern.IsMatch(entry.UserName)) - { - usernamematch = true; - break; - } - } - } - - if (!usernamematch) - { - return usernamematch; - } - } - - if (_isDateSpecified) - { - _isThrowError = false; - bool datematch = false; - if (!_after.Equals(_initial) && _before.Equals(_initial)) - { - if (entry.TimeGenerated > _after) - { - datematch = true; - } - } - else if (!_before.Equals(_initial) && _after.Equals(_initial)) - { - if (entry.TimeGenerated < _before) - { - datematch = true; - } - } - else if (!_after.Equals(_initial) && !_before.Equals(_initial)) - { - if (_after > _before || _after == _before) - { - if ((entry.TimeGenerated > _after) || (entry.TimeGenerated < _before)) - datematch = true; - } - else - { - if ((entry.TimeGenerated > _after) && (entry.TimeGenerated < _before)) - { - datematch = true; - } - } - } - - if (!datematch) - { - return datematch; - } - } - - return true; - } - - private List GetMatchingLogs(string pattern) - { - WildcardPattern wildcardPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - List matchingLogs = new List(); - if (ComputerName.Length == 0) - { - foreach (EventLog log in EventLog.GetEventLogs()) - { - if (wildcardPattern.IsMatch(log.Log)) - { - matchingLogs.Add(log); - } - } - } - else - { - foreach (string computerName in ComputerName) - { - foreach (EventLog log in EventLog.GetEventLogs(computerName)) - { - if (wildcardPattern.IsMatch(log.Log)) - { - matchingLogs.Add(log); - } - } - } - } - - return matchingLogs; - } - // private string ErrorBase = "EventlogResources"; - private DateTime _initial = new DateTime(); - - #endregion Private - } - #endregion GetEventLogCommand - - #region ClearEventLogCommand - /// - /// This class implements the Clear-EventLog command. - /// - - [Cmdlet(VerbsCommon.Clear, "EventLog", SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135198", RemotingCapability = RemotingCapability.SupportedByCommand)] - public sealed class ClearEventLogCommand : PSCmdlet - { - #region Parameters - /// - /// Clear these logs. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] - [Alias("LN")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] LogName { get; set; } - - /// - /// Clear eventlog entries from these Computers. - /// - [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [Alias("Cn")] - public string[] ComputerName { get; set; } = { "." }; - - #endregion Parameters - - #region Overrides - - /// - /// Does the processing. - /// - protected override void BeginProcessing() - { - string computer = string.Empty; - foreach (string compName in ComputerName) - { - if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase))) - { - computer = "localhost"; - } - else - { - computer = compName; - } - - foreach (string eventString in LogName) - { - try - { - if (!EventLog.Exists(eventString, compName)) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, eventString, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - - if (!ShouldProcess(StringUtil.Format(EventlogResources.ClearEventLogWarning, eventString, computer))) - { - continue; - } - - EventLog Log = new EventLog(eventString, compName); - Log.Clear(); - } - catch (System.IO.IOException) - { - ErrorRecord er = new ErrorRecord(new System.IO.IOException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - catch (Win32Exception) - { - ErrorRecord er = new ErrorRecord(new Win32Exception(StringUtil.Format(EventlogResources.NoAccess, null, computer)), null, ErrorCategory.PermissionDenied, null); - WriteError(er); - continue; - } - catch (InvalidOperationException) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.OSWritingError)), null, ErrorCategory.ReadError, null); - WriteError(er); - continue; - } - } - } - } - - // beginprocessing - - #endregion Overrides - } - #endregion ClearEventLogCommand - - #region WriteEventLogCommand - /// - /// This class implements the Write-EventLog command. - /// - - [Cmdlet(VerbsCommunications.Write, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135281", RemotingCapability = RemotingCapability.SupportedByCommand)] - public sealed class WriteEventLogCommand : PSCmdlet - { - #region Parameters - /// - /// Write eventlog entries in this log. - /// - [Parameter(Position = 0, Mandatory = true)] - [Alias("LN")] - [ValidateNotNullOrEmpty] - public string LogName { get; set; } - - /// - /// The source by which the application is registered on the specified computer. - /// - [Parameter(Position = 1, Mandatory = true)] - [Alias("SRC")] - [ValidateNotNullOrEmpty] - public string Source { get; set; } - - /// - /// String which represents One of the EventLogEntryType values. - /// - [Parameter(Position = 3)] - [Alias("ET")] - [ValidateNotNullOrEmpty] - [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })] - public EventLogEntryType EntryType { get; set; } = EventLogEntryType.Information; - - /// - /// The application-specific subcategory associated with the message. - /// - [Parameter] - public Int16 Category { get; set; } = 1; - - /// - /// The application-specific identifier for the event. - /// - [Parameter(Position = 2, Mandatory = true)] - [Alias("ID", "EID")] - [ValidateNotNullOrEmpty] - [ValidateRange(0, UInt16.MaxValue)] - public Int32 EventId { get; set; } - - /// - /// The message goes here. - /// - [Parameter(Position = 4, Mandatory = true)] - [Alias("MSG")] - [ValidateNotNullOrEmpty] - [ValidateLength(0, 32766)] - public string Message { get; set; } - - /// - /// Write eventlog entries of this log. - /// - [Parameter] - [Alias("RD")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public byte[] RawData { get; set; } - - /// - /// Write eventlog entries of this log. - /// - [Parameter] - [Alias("CN")] - [ValidateNotNullOrEmpty] - - public string ComputerName { get; set; } = "."; - - #endregion Parameters - #region private - - private void WriteNonTerminatingError(Exception exception, string errorId, string errorMessage, - ErrorCategory category) - { - Exception ex = new Exception(errorMessage, exception); - WriteError(new ErrorRecord(ex, errorId, category, null)); - } - - #endregion private - #region Overrides - - /// - /// Does the processing. - /// - protected override void BeginProcessing() - { - string _computerName = string.Empty; - if ((ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (ComputerName.Equals(".", StringComparison.OrdinalIgnoreCase))) - { - _computerName = "localhost"; - } - else - { - _computerName = ComputerName; - } - - try - { - if (!(EventLog.SourceExists(Source, ComputerName))) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, null, _computerName, Source)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - } - else - { - if (!(EventLog.Exists(LogName, ComputerName))) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, LogName, _computerName)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - } - else - { - EventLog _myevent = new EventLog(LogName, ComputerName, Source); - _myevent.WriteEntry(Message, EntryType, EventId, Category, RawData); - } - } - } - catch (ArgumentException ex) - { - WriteNonTerminatingError(ex, ex.Message, ex.Message, ErrorCategory.InvalidOperation); - } - catch (InvalidOperationException ex) - { - WriteNonTerminatingError(ex, "AccessDenied", StringUtil.Format(EventlogResources.AccessDenied, LogName, null, Source), ErrorCategory.PermissionDenied); - } - catch (Win32Exception ex) - { - WriteNonTerminatingError(ex, "OSWritingError", StringUtil.Format(EventlogResources.OSWritingError, null, null, null), ErrorCategory.WriteError); - } - catch (System.IO.IOException ex) - { - WriteNonTerminatingError(ex, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, null, ComputerName, null), ErrorCategory.InvalidOperation); - } - } - - #endregion Overrides - } - #endregion WriteEventLogCommand - - #region LimitEventLogCommand - /// - /// This class implements the Limit-EventLog command. - /// - - [Cmdlet(VerbsData.Limit, "EventLog", SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135227", RemotingCapability = RemotingCapability.SupportedByCommand)] - public sealed class LimitEventLogCommand : PSCmdlet - { - #region Parameters - /// - /// Limit the properties of this log. - /// - [Parameter(Position = 0, Mandatory = true)] - [Alias("LN")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] LogName { get; set; } - - /// - /// Limit eventlog entries of this computer. - /// - [Parameter] - [Alias("CN")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName { get; set; } = { "." }; - - /// - /// Minimum retention days for this log. - /// - [Parameter] - [Alias("MRD")] - [ValidateNotNullOrEmpty] - [ValidateRange(1, 365)] - public Int32 RetentionDays - { - get { return _retention; } - - set - { - _retention = value; - _retentionSpecified = true; - } - } - - private Int32 _retention; - private bool _retentionSpecified = false; - /// - /// Overflow action to be taken. - /// - [Parameter] - [Alias("OFA")] - [ValidateNotNullOrEmpty] - [ValidateSetAttribute(new string[] { "OverwriteOlder", "OverwriteAsNeeded", "DoNotOverwrite" })] - - public System.Diagnostics.OverflowAction OverflowAction - { - get { return _overflowaction; } - - set - { - _overflowaction = value; - _overflowSpecified = true; - } - } - - private System.Diagnostics.OverflowAction _overflowaction; - private bool _overflowSpecified = false; - /// - /// Maximum size of this log. - /// - [Parameter] - [ValidateNotNullOrEmpty] - public Int64 MaximumSize - { - get { return _maximumKilobytes; } - - set - { - _maximumKilobytes = value; - _maxkbSpecified = true; - } - } - - private Int64 _maximumKilobytes; - private bool _maxkbSpecified = false; - #endregion Parameters - - #region private - private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId, - ErrorCategory category, string _logName, string _compName) - { - Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName), exception); - WriteError(new ErrorRecord(ex, errorId, category, null)); - } - - #endregion private - - #region Overrides - - /// - /// Does the processing. - /// - protected override - void - BeginProcessing() - { - string computer = string.Empty; - foreach (string compname in ComputerName) - { - if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase))) - { - computer = "localhost"; - } - else - { - computer = compname; - } - - foreach (string logname in LogName) - { - try - { - if (!EventLog.Exists(logname, compname)) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, logname, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - else - { - if (!ShouldProcess(StringUtil.Format(EventlogResources.LimitEventLogWarning, logname, computer))) - { - continue; - } - else - { - EventLog newLog = new EventLog(logname, compname); - int _minRetention = newLog.MinimumRetentionDays; - System.Diagnostics.OverflowAction _newFlowAction = newLog.OverflowAction; - if (_retentionSpecified && _overflowSpecified) - { - if (_overflowaction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) - { - newLog.ModifyOverflowPolicy(_overflowaction, _retention); - } - else - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - else if (_retentionSpecified && !_overflowSpecified) - { - if (_newFlowAction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) - { - newLog.ModifyOverflowPolicy(_newFlowAction, _retention); - } - else - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - else if (!_retentionSpecified && _overflowSpecified) - { - newLog.ModifyOverflowPolicy(_overflowaction, _minRetention); - } - - if (_maxkbSpecified) - { - int kiloByte = 1024; - _maximumKilobytes = _maximumKilobytes / kiloByte; - newLog.MaximumKilobytes = _maximumKilobytes; - } - } - } - } - catch (InvalidOperationException ex) - { - WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, logname, computer); - continue; - } - catch (System.IO.IOException ex) - { - WriteNonTerminatingError(ex, EventlogResources.PathDoesNotExist, "PathDoesNotExist", ErrorCategory.InvalidOperation, null, computer); - continue; - } - catch (ArgumentOutOfRangeException ex) - { - if (!_retentionSpecified && !_maxkbSpecified) - { - WriteNonTerminatingError(ex, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null); - } - else - { - WriteNonTerminatingError(ex, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null); - } - - continue; - } - } - } - } - #endregion override - - } - #endregion LimitEventLogCommand - - #region ShowEventLogCommand - /// - /// This class implements the Show-EventLog command. - /// - - [Cmdlet(VerbsCommon.Show, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135257", RemotingCapability = RemotingCapability.SupportedByCommand)] - public sealed class ShowEventLogCommand : PSCmdlet - { - #region Parameters - - /// - /// Show eventviewer of this computer. - /// - [Parameter(Position = 0)] - [Alias("CN")] - [ValidateNotNullOrEmpty] - - public string ComputerName { get; set; } = "."; - - #endregion Parameters - - #region Overrides - - /// - /// Does the processing. - /// - protected override - void - BeginProcessing() - { - try - { - string eventVwrExe = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), - "eventvwr.exe"); - Process.Start(eventVwrExe, ComputerName); - } - catch (Win32Exception e) - { - if (e.NativeErrorCode.Equals(0x00000002)) - { - string message = StringUtil.Format(EventlogResources.NotSupported); - InvalidOperationException ex = new InvalidOperationException(message); - ErrorRecord er = new ErrorRecord(ex, "Win32Exception", ErrorCategory.InvalidOperation, null); - WriteError(er); - } - else - { - ErrorRecord er = new ErrorRecord(e, "Win32Exception", ErrorCategory.InvalidArgument, null); - WriteError(er); - } - } - catch (SystemException ex) - { - ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, ComputerName); - WriteError(er); - } - } - #endregion override - } - #endregion ShowEventLogCommand - - #region NewEventLogCommand - /// - /// This cmdlet creates the new event log .This cmdlet can also be used to - /// configure a new source for writing entries to an event log on the local - /// computer or a remote computer. - /// You can create an event source for an existing event log or a new event log. - /// When you create a new source for a new event log, the system registers the - /// source for that log, but the log is not created until the first entry is - /// written to it. - /// The operating system stores event logs as files. The associated file is - /// stored in the %SystemRoot%\System32\Config directory on the specified - /// computer. The file name is set by appending the first 8 characters of the - /// Log property with the ".evt" file name extension. - /// You can register the event source with localized resource file(s) for your - /// event category and message strings. Your application can write event log - /// entries using resource identifiers, rather than specifying the actual - /// string. You can register a separate file for event categories, messages and - /// parameter insertion strings, or you can register the same resource file for - /// all three types of strings. - /// - - [Cmdlet(VerbsCommon.New, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135235", RemotingCapability = RemotingCapability.SupportedByCommand)] - public class NewEventLogCommand : PSCmdlet - { - #region Parameter - /// - /// The following is the definition of the input parameter "CategoryResourceFile". - /// Specifies the path of the resource file that contains category strings for - /// the source - /// Resource File is expected to be present in Local/Remote Machines. - /// - [Parameter] - [ValidateNotNullOrEmpty] - [Alias("CRF")] - public string CategoryResourceFile { get; set; } - - /// - /// The following is the definition of the input parameter "ComputerName". - /// Specify the Computer Name. The default is local computer. - /// - [Parameter(Position = 2)] - [ValidateNotNullOrEmpty] - [Alias("CN")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName { get; set; } = { "." }; - - /// - /// The following is the definition of the input parameter "LogName". - /// Specifies the name of the log. - /// - [Parameter(Mandatory = true, - Position = 0)] - [ValidateNotNullOrEmpty] - [Alias("LN")] - public string LogName { get; set; } - - /// - /// The following is the definition of the input parameter "MessageResourceFile". - /// Specifies the path of the message resource file that contains message - /// formatting strings for the source - /// Resource File is expected to be present in Local/Remote Machines. - /// - [Parameter] - [ValidateNotNullOrEmpty] - [Alias("MRF")] - public string MessageResourceFile { get; set; } - - /// - /// The following is the definition of the input parameter "ParameterResourceFile". - /// Specifies the path of the resource file that contains message parameter - /// strings for the source - /// Resource File is expected to be present in Local/Remote Machines. - /// - [Parameter] - [ValidateNotNullOrEmpty] - [Alias("PRF")] - public string ParameterResourceFile { get; set; } - - /// - /// The following is the definition of the input parameter "Source". - /// Specifies the Source of the EventLog. - /// - [Parameter(Mandatory = true, - Position = 1)] - [ValidateNotNullOrEmpty] - [Alias("SRC")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Source { get; set; } - - #endregion Parameter - - #region private - private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId, - ErrorCategory category, string _logName, string _compName, string _source, string _resourceFile) - { - Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName, _source, _resourceFile), exception); - WriteError(new ErrorRecord(ex, errorId, category, null)); - } - - #endregion private - - #region override - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - string computer = string.Empty; - foreach (string compname in ComputerName) - { - if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase))) - { - computer = "localhost"; - } - else - { - computer = compname; - } - - try - { - foreach (string _sourceName in Source) - { - if (!EventLog.SourceExists(_sourceName, compname)) - { - EventSourceCreationData newEventSource = new EventSourceCreationData(_sourceName, LogName); - newEventSource.MachineName = compname; - if (!string.IsNullOrEmpty(MessageResourceFile)) - newEventSource.MessageResourceFile = MessageResourceFile; - if (!string.IsNullOrEmpty(ParameterResourceFile)) - newEventSource.ParameterResourceFile = ParameterResourceFile; - if (!string.IsNullOrEmpty(CategoryResourceFile)) - newEventSource.CategoryResourceFile = CategoryResourceFile; - EventLog.CreateEventSource(newEventSource); - } - else - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceExistInComp, null, computer, _sourceName)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - } - catch (InvalidOperationException ex) - { - WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, LogName, computer, null, null); - continue; - } - catch (ArgumentException ex) - { - ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.InvalidArgument, null); - WriteError(er); - continue; - } - catch (System.Security.SecurityException ex) - { - WriteNonTerminatingError(ex, EventlogResources.AccessIsDenied, "AccessIsDenied", ErrorCategory.InvalidOperation, null, null, null, null); - continue; - } - } - } - // End BeginProcessing() - #endregion override - } - #endregion NewEventLogCommand - - #region RemoveEventLogCommand - /// - /// This cmdlet is used to delete the specified event log from the specified - /// computer. This can also be used to Clear the entries of the specified event - /// log and also to unregister the Source associated with the eventlog. - /// - - [Cmdlet(VerbsCommon.Remove, "EventLog", - SupportsShouldProcess = true, DefaultParameterSetName = "Default", - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135248", RemotingCapability = RemotingCapability.SupportedByCommand)] - public class RemoveEventLogCommand : PSCmdlet - { - /// - /// The following is the definition of the input parameter "ComputerName". - /// Specifies the Computer Name. - /// - [Parameter(Position = 1)] - [ValidateNotNull] - [ValidateNotNullOrEmpty] - [Alias("CN")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName { get; set; } = { "." }; - - /// - /// The following is the definition of the input parameter "LogName". - /// Specifies the Event Log Name. - /// - [Parameter(Mandatory = true, - Position = 0, ParameterSetName = "Default")] - [ValidateNotNull] - [ValidateNotNullOrEmpty] - [Alias("LN")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] LogName { get; set; } - - /// - /// The following is the definition of the input parameter "RemoveSource". - /// Specifies either to remove the event log and associated source or - /// source. alone. - /// When this parameter is not specified, the cmdlet uses Delete Method which - /// clears the eventlog and also the source associated with it. - /// When this parameter value is true, then this cmdlet uses DeleteEventSource - /// Method to delete the Source alone. - /// - [Parameter(ParameterSetName = "Source")] - [ValidateNotNull] - [ValidateNotNullOrEmpty] - [Alias("SRC")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Source { get; set; } - - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - try - { - string computer = string.Empty; - foreach (string compName in ComputerName) - { - if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase))) - { - computer = "localhost"; - } - else - { - computer = compName; - } - - if (ParameterSetName.Equals("Default")) - { - foreach (string log in LogName) - { - try - { - if (EventLog.Exists(log, compName)) - { - if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveEventLogWarning, log, computer))) - { - continue; - } - - EventLog.Delete(log, compName); - } - else - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, log, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - catch (System.IO.IOException) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - } - else - { - foreach (string src in Source) - { - try - { - if (EventLog.SourceExists(src, compName)) - { - if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveSourceWarning, src, computer))) - { - continue; - } - - EventLog.DeleteEventSource(src, compName); - } - else - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, string.Empty, computer, src)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - catch (System.IO.IOException) - { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); - WriteError(er); - continue; - } - } - } - } - } - catch (System.Security.SecurityException ex) - { - ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.SecurityError, null); - WriteError(er); - } - } - } - - #endregion RemoveEventLogCommand -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs deleted file mode 100644 index 6b6551619f1..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Management.Automation; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command that gets the active transaction. - /// - [Cmdlet(VerbsCommon.Get, "Transaction", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135220")] - [OutputType(typeof(PSTransaction))] - public class GetTransactionCommand : PSCmdlet - { - /// - /// Creates a new transaction. - /// - protected override void EndProcessing() - { - WriteObject(this.Context.TransactionManager.GetCurrent()); - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs deleted file mode 100644 index 27f812c7a80..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Globalization; -using System.Management; -using System.Management.Automation; -using System.Text; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command to get WMI Objects. - /// - [Cmdlet(VerbsCommon.Get, "WmiObject", DefaultParameterSetName = "query", - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113337", RemotingCapability = RemotingCapability.OwnedByCommand)] - public class GetWmiObjectCommand : WmiBaseCmdlet - { - #region Parameters - - /// - /// The WMI class to query. - /// - [Alias("ClassName")] - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] - [Parameter(Position = 1, ParameterSetName = "list")] - [ValidateNotNullOrEmpty] - public string Class { get; set; } - - /// - /// To specify whether to get the results recursively. - /// - [Parameter(ParameterSetName = "list")] - public SwitchParameter Recurse { get; set; } = false; - - /// - /// The WMI properties to retrieve. - /// - [Parameter(Position = 1, ParameterSetName = "query")] - [ValidateNotNullOrEmpty] - public string[] Property - { - get { return (string[])_property.Clone(); } - - set { _property = value; } - } - - /// - /// The filter to be used in the search. - /// - [Parameter(ParameterSetName = "query")] - public string Filter { get; set; } - - /// - /// If Amended qualifier to use. - /// - [Parameter] - public SwitchParameter Amended { get; set; } - - /// - /// If Enumerate Deep flag to use. When 'list' parameter is specified 'EnumerateDeep' parameter is ignored. - /// - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - public SwitchParameter DirectRead { get; set; } - - /// - /// The list of classes. - /// - [Parameter(ParameterSetName = "list")] - public SwitchParameter List { get; set; } = false; - - /// - /// The query string to search for objects. - /// - [Parameter(Mandatory = true, ParameterSetName = "WQLQuery")] - public string Query { get; set; } - - #endregion Parameters - - #region parameter data - - private string[] _property = new string[] { "*" }; - - #endregion parameter data - - #region Command code - - /// - /// Uses this.filter, this.wmiClass and this.property to retrieve the filter. - /// - internal string GetQueryString() - { - StringBuilder returnValue = new StringBuilder("select "); - returnValue.Append(string.Join(", ", _property)); - returnValue.Append(" from "); - returnValue.Append(Class); - if (!string.IsNullOrEmpty(Filter)) - { - returnValue.Append(" where "); - returnValue.Append(Filter); - } - - return returnValue.ToString(); - } - /// - /// Uses filter table to convert the class into WMI understandable language. - /// Character Description Example Match Comment - /// * Matches zero or more characters starting at the specified position A* A,ag,Apple Supported by PowerShell. - /// ? Matches any character at the specified position ?n An,in,on (does not match ran) Supported by PowerShell. - /// _ Matches any character at the specified position _n An,in,on (does not match ran) Supported by WMI - /// % Matches zero or more characters starting at the specified position A% A,ag,Apple Supported by WMI - /// [] Matches a range of characters [a-l]ook Book,cook,look (does not match took) Supported by WMI and powershell - /// [] Matches specified characters [bc]ook Book,cook, (does not match look) Supported by WMI and powershell - /// ^ Does not Match specified characters. [^bc]ook Look, took (does not match book, cook) Supported by WMI. - /// - - internal string GetFilterClassName() - { - if (string.IsNullOrEmpty(this.Class)) - return string.Empty; - string filterClass = string.Copy(this.Class); - filterClass = filterClass.Replace('*', '%'); - filterClass = filterClass.Replace('?', '_'); - return filterClass; - } - - internal bool IsLocalizedNamespace(string sNamespace) - { - bool toReturn = false; - if (sNamespace.StartsWith("ms_", StringComparison.OrdinalIgnoreCase)) - { - toReturn = true; - } - - return toReturn; - } - - internal bool ValidateClassFormat() - { - string filterClass = this.Class; - if (string.IsNullOrEmpty(filterClass)) - return true; - StringBuilder newClassName = new StringBuilder(); - for (int i = 0; i < filterClass.Length; i++) - { - if (char.IsLetterOrDigit(filterClass[i]) || - filterClass[i].Equals('[') || filterClass[i].Equals(']') || - filterClass[i].Equals('*') || filterClass[i].Equals('?') || - filterClass[i].Equals('-')) - { - newClassName.Append(filterClass[i]); - continue; - } - else if (filterClass[i].Equals('_')) - { - newClassName.Append('['); - newClassName.Append(filterClass[i]); - newClassName.Append(']'); - continue; - } - - return false; - } - - this.Class = newClassName.ToString(); - return true; - } - - /// - /// Gets the ManagementObjectSearcher object. - /// - internal ManagementObjectSearcher GetObjectList(ManagementScope scope) - { - StringBuilder queryStringBuilder = new StringBuilder(); - if (string.IsNullOrEmpty(this.Class)) - { - queryStringBuilder.Append("select * from meta_class"); - } - else - { - string filterClass = GetFilterClassName(); - if (filterClass == null) - return null; - queryStringBuilder.Append("select * from meta_class where __class like '"); - queryStringBuilder.Append(filterClass); - queryStringBuilder.Append("'"); - } - - ObjectQuery classQuery = new ObjectQuery(queryStringBuilder.ToString()); - - EnumerationOptions enumOptions = new EnumerationOptions(); - enumOptions.EnumerateDeep = true; - enumOptions.UseAmendedQualifiers = this.Amended; - var searcher = new ManagementObjectSearcher(scope, classQuery, enumOptions); - return searcher; - } - /// - /// Gets the properties of an item at the specified path. - /// - protected override void BeginProcessing() - { - ConnectionOptions options = GetConnectionOption(); - if (this.AsJob) - { - RunAsJob("Get-WMIObject"); - return; - } - else - { - if (List.IsPresent) - { - if (!this.ValidateClassFormat()) - { - ErrorRecord errorRecord = new ErrorRecord( - new ArgumentException( - string.Format( - Thread.CurrentThread.CurrentCulture, - "Class", this.Class)), - "INVALID_QUERY_IDENTIFIER", - ErrorCategory.InvalidArgument, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", this.Class); - - WriteError(errorRecord); - return; - } - - foreach (string name in ComputerName) - { - if (this.Recurse.IsPresent) - { - Queue namespaceElement = new Queue(); - namespaceElement.Enqueue(this.Namespace); - while (namespaceElement.Count > 0) - { - string connectNamespace = (string)namespaceElement.Dequeue(); - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options); - try - { - scope.Connect(); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); - WriteError(errorRecord); - continue; - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); - WriteError(errorRecord); - continue; - } - catch (System.UnauthorizedAccessException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); - WriteError(errorRecord); - continue; - } - - ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); - foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) - { - if (!IsLocalizedNamespace((string)obj["Name"])) - { - namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]); - } - } - - ManagementObjectSearcher searcher = this.GetObjectList(scope); - if (searcher == null) - continue; - foreach (ManagementBaseObject obj in searcher.Get()) - { - WriteObject(obj); - } - } - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - try - { - scope.Connect(); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); - WriteError(errorRecord); - continue; - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); - WriteError(errorRecord); - continue; - } - catch (System.UnauthorizedAccessException e) - { - ErrorRecord errorRecord = new ErrorRecord( - e, - "INVALID_NAMESPACE_IDENTIFIER", - ErrorCategory.ObjectNotFound, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); - WriteError(errorRecord); - continue; - } - - ManagementObjectSearcher searcher = this.GetObjectList(scope); - if (searcher == null) - continue; - foreach (ManagementBaseObject obj in searcher.Get()) - { - WriteObject(obj); - } - } - } - - return; - } - - // When -List is not specified and -Recurse is specified, we need the -Class parameter to compose the right query string - if (this.Recurse.IsPresent && string.IsNullOrEmpty(Class)) - { - string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class"); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(errorMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null); - WriteError(er); - return; - } - - string queryString = string.IsNullOrEmpty(this.Query) ? GetQueryString() : this.Query; - ObjectQuery query = new ObjectQuery(queryString.ToString()); - - foreach (string name in ComputerName) - { - try - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - EnumerationOptions enumOptions = new EnumerationOptions(); - enumOptions.UseAmendedQualifiers = Amended; - enumOptions.DirectRead = DirectRead; - ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); - foreach (ManagementBaseObject obj in searcher.Get()) - { - WriteObject(obj); - } - } - catch (ManagementException e) - { - ErrorRecord errorRecord = null; - if (e.ErrorCode.Equals(ManagementStatus.InvalidClass)) - { - string className = GetClassNameFromQuery(queryString); - string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, - e.Message, className); - errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidType, null); - } - else if (e.ErrorCode.Equals(ManagementStatus.InvalidQuery)) - { - string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, - e.Message, queryString); - errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); - } - else if (e.ErrorCode.Equals(ManagementStatus.InvalidNamespace)) - { - string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, - e.Message, this.Namespace); - errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); - } - else - { - errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); - } - - WriteError(errorRecord); - continue; - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "GetWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - continue; - } - } - } - } - - /// - /// Get the class name from a query string. - /// - /// - /// - private string GetClassNameFromQuery(string query) - { - System.Management.Automation.Diagnostics.Assert(query.Contains("from"), - "Only get called when ErrorCode is InvalidClass, which means the query string contains 'from' and the class name"); - - if (Class != null) - { - return Class; - } - - int fromIndex = query.IndexOf(" from ", StringComparison.OrdinalIgnoreCase); - string subQuery = query.Substring(fromIndex + " from ".Length); - string className = subQuery.Split(' ')[0]; - return className; - } - - #endregion Command code - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs deleted file mode 100644 index df0c5775ca1..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Management; -using System.Management.Automation; -using System.Management.Automation.Internal; -using System.Management.Automation.Provider; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Text; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command to Invoke WMI Method. - /// - [Cmdlet(VerbsLifecycle.Invoke, "WmiMethod", DefaultParameterSetName = "class", SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113346", RemotingCapability = RemotingCapability.OwnedByCommand)] - public sealed class InvokeWmiMethod : WmiBaseCmdlet - { - #region Parameters - /// - /// The WMI Object to use. - /// - [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] - public ManagementObject InputObject - { - get { return _inputObject; } - - set { _inputObject = value; } - } - /// - /// The WMI Path to use. - /// - [Parameter(ParameterSetName = "path", Mandatory = true)] - public string Path - { - get { return _path; } - - set { _path = value; } - } - /// - /// The WMI class to use. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] - public string Class - { - get { return _className; } - - set { _className = value; } - } - /// - /// The WMI Method to execute. - /// - [Parameter(Position = 1, Mandatory = true)] - public string Name - { - get { return _methodName; } - - set { _methodName = value; } - } - - /// - /// The parameters to the method specified by MethodName. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(Position = 2, ParameterSetName = "class")] - [Parameter(ParameterSetName = "object")] - [Alias("Args")] - public object[] ArgumentList - { - get { return _argumentList; } - - set { _argumentList = value; } - } - - #endregion Parameters - - #region parameter data - private string _path = null; - private string _className = null; - private string _methodName = null; - private ManagementObject _inputObject = null; - private object[] _argumentList = null; - - #endregion parameter data - #region Command code - /// - /// Invoke WMI method given either path,class name or pipeline input. - /// - protected override void ProcessRecord() - { - if (this.AsJob) - { - RunAsJob("Invoke-WMIMethod"); - return; - } - - if (_inputObject != null) - { - object result = null; - ManagementBaseObject inputParameters = null; - try - { - inputParameters = _inputObject.GetMethodParameters(_methodName); - if (_argumentList != null) - { - int inParamCount = _argumentList.Length; - foreach (PropertyData property in inputParameters.Properties) - { - if (inParamCount == 0) - break; - property.Value = _argumentList[_argumentList.Length - inParamCount]; - inParamCount--; - } - } - - if (!ShouldProcess( - StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, - _inputObject["__CLASS"].ToString(), - this.Name) - )) - { - return; - } - - result = _inputObject.InvokeMethod(_methodName, inputParameters, null); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - if (result != null) - { - WriteObject(result); - } - - return; - } - else - { - ConnectionOptions options = GetConnectionOption(); - ManagementPath mPath = null; - object result = null; - ManagementObject mObject = null; - if (_path != null) - { - mPath = new ManagementPath(_path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = this.Namespace; - } - else if (namespaceSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "NamespaceSpecifiedWithPath", - ErrorCategory.InvalidOperation, - this.Namespace)); - } - - if (mPath.Server != "." && serverNameSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "ComputerNameSpecifiedWithPath", - ErrorCategory.InvalidOperation, - ComputerName)); - } - // If server name is specified loop through it. - if (!(mPath.Server == "." && serverNameSpecified)) - { - string[] serverName = new string[] { mPath.Server }; - ComputerName = serverName; - } - } - - foreach (string name in ComputerName) - { - result = null; - try - { - if (_path != null) - { - mPath.Server = name; - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mObject = mClass; - } - else - { - ManagementObject mInstance = new ManagementObject(mPath); - mObject = mInstance; - } - - ManagementScope mScope = new ManagementScope(mPath, options); - mObject.Scope = mScope; - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - ManagementClass mClass = new ManagementClass(_className); - mObject = mClass; - mObject.Scope = scope; - } - - ManagementBaseObject inputParameters = mObject.GetMethodParameters(_methodName); - if (_argumentList != null) - { - int inParamCount = _argumentList.Length; - foreach (PropertyData property in inputParameters.Properties) - { - if (inParamCount == 0) - break; - object argument = PSObject.Base(_argumentList[_argumentList.Length - inParamCount]); - if (property.IsArray) - { - property.Value = MakeBaseObjectArray(argument); - } - else - { - property.Value = argument; - } - - inParamCount--; - } - } - - if (!ShouldProcess( - StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, - mObject["__CLASS"].ToString(), - this.Name) - )) - { - return; - } - - result = mObject.InvokeMethod(_methodName, inputParameters, null); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "InvokeWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - if (result != null) - { - WriteObject(result); - } - } - } - } - - /// - /// Ensure that the argument is a collection containing no PSObjects. - /// - /// - /// - private static object MakeBaseObjectArray(object argument) - { - if (argument == null) - return null; - - IList listArgument = argument as IList; - if (listArgument == null) - { - return new object[] { argument }; - } - - bool needCopy = false; - foreach (object argElement in listArgument) - { - if (argElement is PSObject) - { - needCopy = true; - break; - } - } - - if (needCopy) - { - var copiedArgument = new object[listArgument.Count]; - int index = 0; - foreach (object argElement in listArgument) - { - copiedArgument[index++] = argElement != null ? PSObject.Base(argElement) : null; - } - - return copiedArgument; - } - else - { - return argument; - } - } - - #endregion Command code - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs deleted file mode 100644 index 0d547abfa9d..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Management; -using System.Management.Automation; -using System.Text; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Registers for an event on an object. - /// - [Cmdlet(VerbsLifecycle.Register, "WmiEvent", DefaultParameterSetName = "class", - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135245", RemotingCapability = RemotingCapability.OwnedByCommand)] - public class RegisterWmiEventCommand : ObjectEventRegistrationBase - { - #region parameters - - /// - /// The WMI namespace to use. - /// - [Parameter] - [Alias("NS")] - public string Namespace { get; set; } = "root\\cimv2"; - - /// - /// The credential to use. - /// - [Parameter] - [Credential] - public PSCredential Credential { get; set; } - - /// - /// The ComputerName in which to query. - /// - [Parameter] - [Alias("Cn")] - [ValidateNotNullOrEmpty] - public string ComputerName { get; set; } = "localhost"; - - /// - /// The WMI class to use. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] - public string Class { get; set; } = null; - - /// - /// The query string to search for objects. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] - public string Query { get; set; } = null; - - /// - /// Timeout in milliseconds. - /// - [Parameter] - [Alias("TimeoutMSec")] - public Int64 Timeout - { - get - { - return _timeOut; - } - - set - { - _timeOut = value; - _timeoutSpecified = true; - } - } - - private Int64 _timeOut = 0; - private bool _timeoutSpecified = false; - - #endregion parameters - #region helper functions - private string BuildEventQuery(string objectName) - { - StringBuilder returnValue = new StringBuilder("select * from "); - returnValue.Append(objectName); - return returnValue.ToString(); - } - - private string GetScopeString(string computer, string namespaceParameter) - { - StringBuilder returnValue = new StringBuilder("\\\\"); - returnValue.Append(computer); - returnValue.Append('\\'); - returnValue.Append(namespaceParameter); - return returnValue.ToString(); - } - #endregion helper functions - - /// - /// Returns the object that generates events to be monitored. - /// - protected override object GetSourceObject() - { - string wmiQuery = this.Query; - if (this.Class != null) - { - // Validate class format - for (int i = 0; i < this.Class.Length; i++) - { - if (char.IsLetterOrDigit(this.Class[i]) || this.Class[i].Equals('_')) - { - continue; - } - - ErrorRecord errorRecord = new ErrorRecord( - new ArgumentException( - string.Format( - Thread.CurrentThread.CurrentCulture, - "Class", this.Class)), - "INVALID_QUERY_IDENTIFIER", - ErrorCategory.InvalidArgument, - null); - errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiInvalidClass"); - - ThrowTerminatingError(errorRecord); - return null; - } - - wmiQuery = BuildEventQuery(this.Class); - } - - ConnectionOptions conOptions = new ConnectionOptions(); - if (this.Credential != null) - { - System.Net.NetworkCredential cred = this.Credential.GetNetworkCredential(); - if (string.IsNullOrEmpty(cred.Domain)) - { - conOptions.Username = cred.UserName; - } - else - { - conOptions.Username = cred.Domain + "\\" + cred.UserName; - } - - conOptions.Password = cred.Password; - } - - ManagementScope scope = new ManagementScope(GetScopeString(ComputerName, this.Namespace), conOptions); - EventWatcherOptions evtOptions = new EventWatcherOptions(); - - if (_timeoutSpecified) - { - evtOptions.Timeout = new TimeSpan(_timeOut * 10000); - } - - ManagementEventWatcher watcher = new ManagementEventWatcher(scope, new EventQuery(wmiQuery), evtOptions); - return watcher; - } - - /// - /// Returns the event name to be monitored on the input object. - /// - protected override string GetSourceObjectEventName() - { - return "EventArrived"; - } - - /// - /// Processes the event subscriber after the base class has registered. - /// - protected override void EndProcessing() - { - base.EndProcessing(); - - // Register for the "Unsubscribed" event so that we can stop the - // event watcher. - PSEventSubscriber newSubscriber = NewSubscriber; - if (newSubscriber != null) - { - newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); - } - } - - private void newSubscriber_Unsubscribed(object sender, PSEventUnsubscribedEventArgs e) - { - ManagementEventWatcher watcher = sender as ManagementEventWatcher; - if (watcher != null) - { - watcher.Stop(); - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs deleted file mode 100644 index cce50ea1563..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management; -using System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command to Remove WMI Object. - /// - [Cmdlet(VerbsCommon.Remove, "WmiObject", DefaultParameterSetName = "class", SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113381", RemotingCapability = RemotingCapability.OwnedByCommand)] - public class RemoveWmiObject : WmiBaseCmdlet - { - #region Parameters - /// - /// The WMI Object to use. - /// - [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] - public ManagementObject InputObject - { - get { return _inputObject; } - - set { _inputObject = value; } - } - /// - /// The WMI Path to use. - /// - [Parameter(Mandatory = true, ParameterSetName = "path")] - public string Path - { - get { return _path; } - - set { _path = value; } - } - /// - /// The WMI class to use. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] - public string Class - { - get { return _className; } - - set { _className = value; } - } - - #endregion Parameters - - #region parameter data - private string _path = null; - private string _className = null; - private ManagementObject _inputObject = null; - - #endregion parameter data - #region Command code - /// - /// Remove an object given either path,class name or pipeline input. - /// - protected override void ProcessRecord() - { - if (this.AsJob) - { - RunAsJob("Remove-WMIObject"); - return; - } - - if (_inputObject != null) - { - try - { - if (!ShouldProcess(_inputObject["__PATH"].ToString())) - { - return; - } - - _inputObject.Delete(); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - return; - } - else - { - ConnectionOptions options = GetConnectionOption(); - ManagementPath mPath = null; - ManagementObject mObject = null; - if (_path != null) - { - mPath = new ManagementPath(_path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = this.Namespace; - } - else if (namespaceSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "NamespaceSpecifiedWithPath", - ErrorCategory.InvalidOperation, - this.Namespace)); - } - - if (mPath.Server != "." && serverNameSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "ComputerNameSpecifiedWithPath", - ErrorCategory.InvalidOperation, - this.ComputerName)); - } - - if (!(mPath.Server == "." && serverNameSpecified)) - { - string[] serverName = new string[] { mPath.Server }; - ComputerName = serverName; - } - } - - foreach (string name in ComputerName) - { - try - { - if (_path != null) - { - mPath.Server = name; - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mObject = mClass; - } - else - { - ManagementObject mInstance = new ManagementObject(mPath); - mObject = mInstance; - } - - ManagementScope mScope = new ManagementScope(mPath, options); - mObject.Scope = mScope; - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - ManagementClass mClass = new ManagementClass(_className); - mObject = mClass; - mObject.Scope = scope; - } - - if (!ShouldProcess(mObject["__PATH"].ToString())) - { - continue; - } - - mObject.Delete(); - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - } - } - } - #endregion Command code - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs deleted file mode 100644 index 3d6fc27cc3c..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Management.Automation; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command that rolls back a transaction. - /// - [Cmdlet(VerbsCommon.Undo, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135268")] - public class UndoTransactionCommand : PSCmdlet - { - /// - /// Rolls the current transaction back. - /// - protected override void EndProcessing() - { - // Rollback the transaction - if (ShouldProcess( - NavigationResources.TransactionResource, - NavigationResources.RollbackAction)) - { - this.Context.TransactionManager.Rollback(); - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs deleted file mode 100644 index 4b2deac8bef..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Management; -using System.Management.Automation; -using System.Management.Automation.Provider; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Text; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command to Set WMI Instance. - /// - [Cmdlet(VerbsCommon.Set, "WmiInstance", DefaultParameterSetName = "class", SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113402", RemotingCapability = RemotingCapability.OwnedByCommand)] - public sealed class SetWmiInstance : WmiBaseCmdlet - { - #region Parameters - /// - /// The WMI Object to use. - /// - [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] - public ManagementObject InputObject { get; set; } = null; - - /// - /// The WMI Path to use. - /// - [Parameter(ParameterSetName = "path", Mandatory = true)] - public string Path { get; set; } = null; - - /// - /// The WMI class to use. - /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] - public string Class { get; set; } = null; - - /// - /// The property name /value pair. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(Position = 2, ParameterSetName = "class")] - [Parameter(ParameterSetName = "object")] - [Alias("Args", "Property")] - [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public Hashtable Arguments { get; set; } = null; - - /// - /// The Flag to use. - /// - [Parameter] - public PutType PutType - { - get { return _putType; } - - set { _putType = value; flagSpecified = true; } - } - - #endregion Parameters - #region parameter data - internal bool flagSpecified = false; - private PutType _putType = PutType.None; - - #endregion parameter data - - #region Command code - /// - /// Create or modify WMI Instance given either path,class name or pipeline input. - /// - protected override void ProcessRecord() - { - if (this.AsJob) - { - RunAsJob("Set-WMIInstance"); - return; - } - - if (InputObject != null) - { - object result = null; - ManagementObject mObj = null; - try - { - PutOptions pOptions = new PutOptions(); - mObj = SetWmiInstanceGetPipelineObject(); - pOptions.Type = _putType; - if (mObj != null) - { - if (!ShouldProcess(mObj.Path.Path.ToString())) - { - return; - } - - mObj.Put(pOptions); - } - else - { - InvalidOperationException exp = new InvalidOperationException(); - throw exp; - } - - result = mObj; - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - WriteObject(result); - } - else - { - ManagementPath mPath = null; - // If Class is specified only CreateOnly flag is supported - mPath = this.SetWmiInstanceBuildManagementPath(); - // If server name is specified loop through it. - if (mPath != null) - { - if (!(mPath.Server == "." && serverNameSpecified)) - { - string[] serverName = new string[] { mPath.Server }; - ComputerName = serverName; - } - } - - ConnectionOptions options = GetConnectionOption(); - object result = null; - ManagementObject mObject = null; - foreach (string name in ComputerName) - { - result = null; - try - { - mObject = this.SetWmiInstanceGetObject(mPath, name); - PutOptions pOptions = new PutOptions(); - pOptions.Type = _putType; - if (mObject != null) - { - if (!ShouldProcess(mObject.Path.Path.ToString())) - { - continue; - } - - mObject.Put(pOptions); - } - else - { - InvalidOperationException exp = new InvalidOperationException(); - throw exp; - } - - result = mObject; - } - catch (ManagementException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - catch (System.Runtime.InteropServices.COMException e) - { - ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - if (result != null) - { - WriteObject(result); - } - } - } - } - #endregion Command code - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs deleted file mode 100644 index 58dcfbd1daa..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management.Automation; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command that begins a transaction. - /// - [Cmdlet(VerbsLifecycle.Start, "Transaction", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135262")] - public class StartTransactionCommand : PSCmdlet - { - /// - /// The time, in minutes, before this transaction is rolled back - /// automatically. - /// - [Parameter] - [Alias("TimeoutMins")] - public int Timeout - { - get - { - return (int)_timeout.TotalMinutes; - } - - set - { - // The transactions constructor treats a timeout of - // zero as infinite. So we fudge it to be a bit longer. - if (value == 0) - _timeout = TimeSpan.FromTicks(1); - else - _timeout = TimeSpan.FromMinutes(value); - - _timeoutSpecified = true; - } - } - - private bool _timeoutSpecified = false; - private TimeSpan _timeout = TimeSpan.MinValue; - - /// - /// Gets or sets the flag to determine if this transaction can - /// be committed or rolled back independently of other transactions. - /// - [Parameter] - public SwitchParameter Independent - { - get { return _independent; } - - set { _independent = value; } - } - - private SwitchParameter _independent; - - /// - /// Gets or sets the rollback preference for this transaction. - /// - [Parameter] - public RollbackSeverity RollbackPreference - { - get { return _rollbackPreference; } - - set { _rollbackPreference = value; } - } - - private RollbackSeverity _rollbackPreference = RollbackSeverity.Error; - - /// - /// Creates a new transaction. - /// - protected override void EndProcessing() - { - if (ShouldProcess( - NavigationResources.TransactionResource, - NavigationResources.CreateAction)) - { - // Set the default timeout - if (!_timeoutSpecified) - { - // See if we're being invoked directly at the - // command line. In that case, set the timeout to infinite. - if (MyInvocation.CommandOrigin == CommandOrigin.Runspace) - { - _timeout = TimeSpan.MaxValue; - } - else - { - _timeout = TimeSpan.FromMinutes(30); - } - } - - // Create the new transaction - if (_independent) - { - this.Context.TransactionManager.CreateNew(_rollbackPreference, _timeout); - } - else - { - this.Context.TransactionManager.CreateOrJoin(_rollbackPreference, _timeout); - } - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs deleted file mode 100644 index 67d3acee44a..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management.Automation; -using System.Management.Automation.Internal; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// A command that commits a transaction. - /// - [Cmdlet(VerbsOther.Use, "Transaction", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135271")] - public class UseTransactionCommand : PSCmdlet - { - /// - /// This parameter specifies the script block to run in the current - /// PowerShell transaction. - /// - [Parameter(Position = 0, Mandatory = true)] - public ScriptBlock TransactedScript - { - get - { - return _transactedScript; - } - - set - { - _transactedScript = value; - } - } - - private ScriptBlock _transactedScript; - - /// - /// Commits the current transaction. - /// - protected override void EndProcessing() - { - using (CurrentPSTransaction) - { - try - { - var emptyArray = Array.Empty(); - _transactedScript.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: null, - input: emptyArray, - scriptThis: AutomationNull.Value, - args: emptyArray); - } - catch (Exception e) - { - // Catch-all OK. This is a third-party call-out. - - ErrorRecord errorRecord = new ErrorRecord(e, "TRANSACTED_SCRIPT_EXCEPTION", ErrorCategory.NotSpecified, null); - - // The "transaction timed out" exception is - // exceedingly obtuse. We clarify things here. - bool isTimeoutException = false; - Exception tempException = e; - while (tempException != null) - { - if (tempException is System.TimeoutException) - { - isTimeoutException = true; - break; - } - - tempException = tempException.InnerException; - } - - if (isTimeoutException) - { - errorRecord = new ErrorRecord( - new InvalidOperationException( - TransactionResources.TransactionTimedOut), - "TRANSACTION_TIMEOUT", - ErrorCategory.InvalidOperation, - e); - } - - WriteError(errorRecord); - } - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs deleted file mode 100644 index 31670a7d632..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ /dev/null @@ -1,2083 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Management; -using System.Management.Automation; -using System.Management.Automation.Internal; -using System.Management.Automation.Provider; -using System.Management.Automation.Remoting; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Text; -using System.Threading; - -using Microsoft.PowerShell.Commands.Internal; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - #region Helper Classes - - /// - /// Base class for all WMI helper classes. This is an abstract class - /// and the helpers need to derive from this. - /// - internal abstract class AsyncCmdletHelper : IThrottleOperation - { - /// - /// Exception raised internally when any method of this class - /// is executed. - /// - internal Exception InternalException - { - get - { - return internalException; - } - } - - protected Exception internalException = null; - } - - /// - /// This class is responsible for creating WMI connection for getting objects and notifications - /// from WMI asynchronously. This spawns a new thread to connect to WMI on remote machine. - /// This allows the main thread to return faster and not blocked on network hops. - /// - internal class WmiAsyncCmdletHelper : AsyncCmdletHelper - { - /// - /// Internal Constructor. - /// - /// Job associated with this operation. - /// Object associated with this operation. - /// Computer on which the operation is invoked. - /// Sink to get wmi objects. - internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results) - { - _wmiObject = wmiObject; - _computerName = computerName; - _results = results; - this.State = WmiState.NotStarted; - _job = childJob; - } - - /// - /// Internal Constructor. This variant takes a count parameter that determines how many times - /// the WMI command is executed. - /// - /// Job associated with this operation. - /// Object associated with this operation. - /// Computer on which the operation is invoked. - /// Sink to return wmi objects. - /// Number of times the WMI command is executed. - internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results, int count) - : this(childJob, wmiObject, computerName, results) - { - _cmdCount = count; - } - - private string _computerName; - internal event EventHandler WmiOperationState; - internal event EventHandler ShutdownComplete; - private ManagementOperationObserver _results; - private int _cmdCount = 1; - private PSWmiChildJob _job; - /// - /// Current operation state. - /// - internal WmiState State - { - get { return _state; } - - set { _state = value; } - } - - private WmiState _state; - - /// - /// Cancel WMI connection. - /// - internal override void StopOperation() - { - _results.Cancel(); - _state = WmiState.Stopped; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - /// - /// Uses this.filter, this.wmiClass and this.property to retrieve the filter. - /// - private string GetWmiQueryString() - { - GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject; - StringBuilder returnValue = new StringBuilder("select "); - returnValue.Append(string.Join(", ", getObject.Property)); - returnValue.Append(" from "); - returnValue.Append(getObject.Class); - if (!string.IsNullOrEmpty(getObject.Filter)) - { - returnValue.Append(" where "); - returnValue.Append(getObject.Filter); - } - - return returnValue.ToString(); - } - - /// - /// Do WMI connection by creating another thread based on type of request and return immediately. - /// - internal override void StartOperation() - { - Thread thread; - if (_wmiObject.GetType() == typeof(GetWmiObjectCommand)) - { - thread = new Thread(new ThreadStart(ConnectGetWMI)); - } - else if (_wmiObject.GetType() == typeof(RemoveWmiObject)) - { - thread = new Thread(new ThreadStart(ConnectRemoveWmi)); - } - else if (_wmiObject is InvokeWmiMethod) - { - thread = new Thread(new ThreadStart(ConnectInvokeWmi)); - } - else if (_wmiObject is SetWmiInstance) - { - thread = new Thread(new ThreadStart(ConnectSetWmi)); - } - else - { - InvalidOperationException exception = new InvalidOperationException("This operation is not supported for this cmdlet."); - internalException = exception; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - } - - /// - /// - internal override event EventHandler OperationComplete; - - private Cmdlet _wmiObject; - - /// - /// Raise operation completion event. - /// - internal void RaiseOperationCompleteEvent(EventArgs baseEventArgs, OperationState state) - { - OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); - operationStateEventArgs.OperationState = state; - OperationComplete.SafeInvoke(this, operationStateEventArgs); - } - - /// - /// Raise WMI state changed event - /// - internal void RaiseWmiOperationState(EventArgs baseEventArgs, WmiState state) - { - WmiJobStateEventArgs wmiJobStateEventArgs = new WmiJobStateEventArgs(); - wmiJobStateEventArgs.WmiState = state; - WmiOperationState.SafeInvoke(this, wmiJobStateEventArgs); - } - - /// - /// Do the actual connection to remote machine for Set-WMIInstance cmdlet and raise operation complete event. - /// - private void ConnectSetWmi() - { - SetWmiInstance setObject = (SetWmiInstance)_wmiObject; - _state = WmiState.Running; - RaiseWmiOperationState(null, WmiState.Running); - if (setObject.InputObject != null) - { - ManagementObject mObj = null; - try - { - PutOptions pOptions = new PutOptions(); - // Extra check - if (setObject.InputObject.GetType() == typeof(ManagementClass)) - { - // Check if Flag specified is CreateOnly or not - if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) - { - InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - mObj = ((ManagementClass)setObject.InputObject).CreateInstance(); - setObject.PutType = PutType.CreateOnly; - } - else - { - // Check if Flag specified is Updateonly or UpdateOrCreateOnly or not - if (setObject.flagSpecified) - { - if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) - { - InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - } - else - { - setObject.PutType = PutType.UpdateOrCreate; - } - - mObj = (ManagementObject)setObject.InputObject.Clone(); - } - - if (setObject.Arguments != null) - { - IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - mObj[en.Key as string] = en.Value; - } - } - - pOptions.Type = setObject.PutType; - if (mObj != null) - { - mObj.Put(_results, pOptions); - } - else - { - InvalidOperationException exp = new InvalidOperationException(); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - else - { - ManagementPath mPath = null; - // If Class is specified only CreateOnly flag is supported - if (setObject.Class != null) - { - if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) - { - InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - setObject.PutType = PutType.CreateOnly; - } - else - { - mPath = new ManagementPath(setObject.Path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = setObject.Namespace; - } - else if (setObject.namespaceSpecified) - { - InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath"); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - if (mPath.Server != "." && setObject.serverNameSpecified) - { - InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath"); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - if (mPath.IsClass) - { - if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) - { - InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - setObject.PutType = PutType.CreateOnly; - } - else - { - if (setObject.flagSpecified) - { - if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) - { - InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - } - else - { - setObject.PutType = PutType.UpdateOrCreate; - } - } - } - // If server name is specified loop through it. - if (mPath != null) - { - if (!(mPath.Server == "." && setObject.serverNameSpecified)) - { - _computerName = mPath.Server; - } - } - - ConnectionOptions options = setObject.GetConnectionOption(); - ManagementObject mObject = null; - try - { - if (setObject.Path != null) - { - mPath.Server = _computerName; - ManagementScope mScope = new ManagementScope(mPath, options); - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mClass.Scope = mScope; - mObject = mClass.CreateInstance(); - } - else - { - // This can throw if path does not exist caller should catch it. - ManagementObject mInstance = new ManagementObject(mPath); - mInstance.Scope = mScope; - try - { - mInstance.Get(); - } - catch (ManagementException e) - { - if (e.ErrorCode != ManagementStatus.NotFound) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - int namespaceIndex = setObject.Path.IndexOf(':'); - if (namespaceIndex == -1) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); - if (classIndex == -1) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - // Get class object and create instance. - string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); - ManagementPath classPath = new ManagementPath(newPath); - ManagementClass mClass = new ManagementClass(classPath); - mClass.Scope = mScope; - mInstance = mClass.CreateInstance(); - } - - mObject = mInstance; - } - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options); - ManagementClass mClass = new ManagementClass(setObject.Class); - mClass.Scope = scope; - mObject = mClass.CreateInstance(); - } - - if (setObject.Arguments != null) - { - IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - mObject[en.Key as string] = en.Value; - } - } - - PutOptions pOptions = new PutOptions(); - pOptions.Type = setObject.PutType; - if (mObject != null) - { - mObject.Put(_results, pOptions); - } - else - { - InvalidOperationException exp = new InvalidOperationException(); - internalException = exp; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - } - - /// - /// Do the actual connection to remote machine for Invoke-WMIMethod cmdlet and raise operation complete event. - /// - private void ConnectInvokeWmi() - { - InvokeWmiMethod invokeObject = (InvokeWmiMethod)_wmiObject; - _state = WmiState.Running; - RaiseWmiOperationState(null, WmiState.Running); - - if (invokeObject.InputObject != null) - { - ManagementBaseObject inputParameters = null; - try - { - inputParameters = invokeObject.InputObject.GetMethodParameters(invokeObject.Name); - if (invokeObject.ArgumentList != null) - { - int inParamCount = invokeObject.ArgumentList.Length; - foreach (PropertyData property in inputParameters.Properties) - { - if (inParamCount == 0) - break; - property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount]; - inParamCount--; - } - } - - invokeObject.InputObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - - return; - } - else - { - ConnectionOptions options = invokeObject.GetConnectionOption(); - ManagementPath mPath = null; - ManagementObject mObject = null; - if (invokeObject.Path != null) - { - mPath = new ManagementPath(invokeObject.Path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = invokeObject.Namespace; - } - else if (invokeObject.namespaceSpecified) - { - InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - if (mPath.Server != "." && invokeObject.serverNameSpecified) - { - InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - // If server name is specified loop through it. - if (!(mPath.Server == "." && invokeObject.serverNameSpecified)) - { - _computerName = mPath.Server; - } - } - - bool isLocal = false, needToEnablePrivilege = false; - PlatformInvokes.TOKEN_PRIVILEGE currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); - try - { - needToEnablePrivilege = NeedToEnablePrivilege(_computerName, invokeObject.Name, ref isLocal); - if (needToEnablePrivilege) - { - if (!(isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) && - !(!isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState))) - { - string message = - StringUtil.Format(ComputerResources.PrivilegeNotEnabled, _computerName, - isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); - InvalidOperationException e = new InvalidOperationException(message); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - } - - if (invokeObject.Path != null) - { - mPath.Server = _computerName; - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mObject = mClass; - } - else - { - ManagementObject mInstance = new ManagementObject(mPath); - mObject = mInstance; - } - - ManagementScope mScope = new ManagementScope(mPath, options); - mObject.Scope = mScope; - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, invokeObject.Namespace), options); - ManagementClass mClass = new ManagementClass(invokeObject.Class); - mObject = mClass; - mObject.Scope = scope; - } - - ManagementBaseObject inputParameters = mObject.GetMethodParameters(invokeObject.Name); - if (invokeObject.ArgumentList != null) - { - int inParamCount = invokeObject.ArgumentList.Length; - foreach (PropertyData property in inputParameters.Properties) - { - if (inParamCount == 0) - break; - property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount]; - inParamCount--; - } - } - - if (needToEnablePrivilege) - { - ManagementBaseObject result = mObject.InvokeMethod(invokeObject.Name, inputParameters, null); - Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked"); - int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture); - if (returnCode != 0) - { - var e = new Win32Exception(returnCode); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - else - { - ShutdownComplete.SafeInvoke(this, null); - } - } - else - { - mObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); - } - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - finally - { - // Restore the previous privilege state if something unexpected happened - if (needToEnablePrivilege) - { - PlatformInvokes.RestoreTokenPrivilege( - isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState); - } - } - } - } - - /// - /// Check if we need to enable the shutdown privilege. - /// - /// - /// - /// - /// - private bool NeedToEnablePrivilege(string computer, string methodName, ref bool isLocal) - { - bool result = false; - if (methodName.Equals("Win32Shutdown", StringComparison.OrdinalIgnoreCase)) - { - result = true; - - // CLR 4.0 Port note - use https://msdn.microsoft.com/library/system.net.networkinformation.ipglobalproperties.hostname(v=vs.110).aspx - string localName = System.Net.Dns.GetHostName(); - - // And for this, use PsUtils.GetHostname() - string localFullName = System.Net.Dns.GetHostEntry(string.Empty).HostName; - if (computer.Equals(".") || computer.Equals("localhost", StringComparison.OrdinalIgnoreCase) || - computer.Equals(localName, StringComparison.OrdinalIgnoreCase) || - computer.Equals(localFullName, StringComparison.OrdinalIgnoreCase)) - { - isLocal = true; - } - } - - return result; - } - - /// - /// Do the actual connection to remote machine for Remove-WMIObject cmdlet and raise operation complete event. - /// - private void ConnectRemoveWmi() - { - RemoveWmiObject removeObject = (RemoveWmiObject)_wmiObject; - _state = WmiState.Running; - RaiseWmiOperationState(null, WmiState.Running); - if (removeObject.InputObject != null) - { - try - { - removeObject.InputObject.Delete(_results); - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - - return; - } - else - { - ConnectionOptions options = removeObject.GetConnectionOption(); - ManagementPath mPath = null; - ManagementObject mObject = null; - if (removeObject.Path != null) - { - mPath = new ManagementPath(removeObject.Path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = removeObject.Namespace; - } - else if (removeObject.namespaceSpecified) - { - InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - if (mPath.Server != "." && removeObject.serverNameSpecified) - { - InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - if (!(mPath.Server == "." && removeObject.serverNameSpecified)) - { - _computerName = mPath.Server; - } - } - - try - { - if (removeObject.Path != null) - { - mPath.Server = _computerName; - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mObject = mClass; - } - else - { - ManagementObject mInstance = new ManagementObject(mPath); - mObject = mInstance; - } - - ManagementScope mScope = new ManagementScope(mPath, options); - mObject.Scope = mScope; - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, removeObject.Namespace), options); - ManagementClass mClass = new ManagementClass(removeObject.Class); - mObject = mClass; - mObject.Scope = scope; - } - - mObject.Delete(_results); - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - } - - /// - /// Do the actual connection to remote machine for Get-WMIObject cmdlet and raise operation complete event. - /// - private void ConnectGetWMI() - { - GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject; - _state = WmiState.Running; - RaiseWmiOperationState(null, WmiState.Running); - ConnectionOptions options = getObject.GetConnectionOption(); - if (getObject.List.IsPresent) - { - if (!getObject.ValidateClassFormat()) - { - ArgumentException e = new ArgumentException( - string.Format( - Thread.CurrentThread.CurrentCulture, - "Class", getObject.Class)); - - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - try - { - if (getObject.Recurse.IsPresent) - { - ArrayList namespaceArray = new ArrayList(); - ArrayList sinkArray = new ArrayList(); - ArrayList connectArray = new ArrayList(); // Optimization for remote namespace - int currentNamespaceCount = 0; - namespaceArray.Add(getObject.Namespace); - bool topNamespace = true; - while (currentNamespaceCount < namespaceArray.Count) - { - string connectNamespace = (string)namespaceArray[currentNamespaceCount]; - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, connectNamespace), options); - scope.Connect(); - ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); - foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) - { - if (!getObject.IsLocalizedNamespace((string)obj["Name"])) - { - namespaceArray.Add(connectNamespace + "\\" + obj["Name"]); - } - } - - if (topNamespace) - { - topNamespace = false; - sinkArray.Add(_results); - } - else - { - sinkArray.Add(_job.GetNewSink()); - } - - connectArray.Add(scope); - currentNamespaceCount++; - } - - if ((sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception - { - internalException = new InvalidOperationException(); - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - return; - } - - currentNamespaceCount = 0; - while (currentNamespaceCount < namespaceArray.Count) - { - string connectNamespace = (string)namespaceArray[currentNamespaceCount]; - ManagementObjectSearcher searcher = getObject.GetObjectList((ManagementScope)connectArray[currentNamespaceCount]); - if (searcher == null) - { - currentNamespaceCount++; - continue; - } - - if (topNamespace) - { - topNamespace = false; - searcher.Get(_results); - } - else - { - searcher.Get((ManagementOperationObserver)sinkArray[currentNamespaceCount]); - } - - currentNamespaceCount++; - } - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options); - scope.Connect(); - ManagementObjectSearcher searcher = getObject.GetObjectList(scope); - if (searcher == null) - throw new ManagementException(); - searcher.Get(_results); - } - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - - return; - } - - string queryString = string.IsNullOrEmpty(getObject.Query) ? GetWmiQueryString() : getObject.Query; - ObjectQuery query = new ObjectQuery(queryString.ToString()); - try - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options); - EnumerationOptions enumOptions = new EnumerationOptions(); - enumOptions.UseAmendedQualifiers = getObject.Amended; - enumOptions.DirectRead = getObject.DirectRead; - ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); - - // Execute the WMI command for each count value. - for (int i = 0; i < _cmdCount; ++i) - { - searcher.Get(_results); - } - } - catch (ManagementException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.Runtime.InteropServices.COMException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - catch (System.UnauthorizedAccessException e) - { - internalException = e; - _state = WmiState.Failed; - RaiseOperationCompleteEvent(null, OperationState.StopComplete); - } - } - } - - /// - /// Event which will be triggered when WMI state is changed. - /// Currently it is to notify Jobs that state has changed to running. - /// Other states are notified via OperationComplete. - /// - internal sealed class WmiJobStateEventArgs : EventArgs - { - /// - /// WMI state - /// - internal WmiState WmiState { get; set; } - } - - /// - /// Enumerated type defining the state of the WMI operation. - /// - public enum WmiState - { - /// - /// The operation has not been started. - /// - NotStarted = 0, - /// - /// The operation is executing. - /// - Running = 1, - /// - /// The operation is stoping execution. - /// - Stopping = 2, - /// - /// The operation is completed due to a stop request. - /// - Stopped = 3, - /// - /// The operation has completed. - /// - Completed = 4, - /// - /// The operation completed abnormally due to an error. - /// - Failed = 5, - } - - internal static class WMIHelper - { - internal static string GetScopeString(string computer, string namespaceParameter) - { - StringBuilder returnValue = new StringBuilder("\\\\"); - returnValue.Append(computer); - returnValue.Append('\\'); - returnValue.Append(namespaceParameter); - return returnValue.ToString(); - } - } - #endregion Helper Classes - - /// - /// A class to set WMI connection options. - /// - public class WmiBaseCmdlet : Cmdlet - { - #region Parameters - - /// - /// Perform Async operation. - /// - [Parameter] - public SwitchParameter AsJob { get; set; } = false; - - /// - /// The Impersonation level to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - public ImpersonationLevel Impersonation { get; set; } = ImpersonationLevel.Impersonate; - - /// - /// The Authentication level to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - public AuthenticationLevel Authentication { get; set; } = AuthenticationLevel.PacketPrivacy; - - /// - /// The Locale to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - public string Locale { get; set; } = null; - - /// - /// If all Privileges are enabled. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - public SwitchParameter EnableAllPrivileges { get; set; } - - /// - /// The Authority to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - public string Authority { get; set; } = null; - - /// - /// The credential to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - [Credential] - public PSCredential Credential { get; set; } - - /// - /// The credential to use. - /// - [Parameter] - public Int32 ThrottleLimit { get; set; } = s_DEFAULT_THROTTLE_LIMIT; - - /// - /// The ComputerName in which to query. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - [ValidateNotNullOrEmpty] - [Alias("Cn")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName - { - get { return _computerName; } - - set { _computerName = value; serverNameSpecified = true; } - } - /// - /// The WMI namespace to use. - /// - [Parameter(ParameterSetName = "path")] - [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName = "WQLQuery")] - [Parameter(ParameterSetName = "query")] - [Parameter(ParameterSetName = "list")] - [Alias("NS")] - public string Namespace - { - get { return _nameSpace; } - - set { _nameSpace = value; namespaceSpecified = true; } - } - #endregion Parameters - - #region parameter data - /// - /// The computer to query. - /// - private string[] _computerName = new string[] { "localhost" }; - /// - /// WMI namespace. - /// - private string _nameSpace = "root\\cimv2"; - /// - /// Specify if namespace was specified or not. - /// - internal bool namespaceSpecified = false; - /// - /// Specify if server name was specified or not. - /// - internal bool serverNameSpecified = false; - - private static int s_DEFAULT_THROTTLE_LIMIT = 32; // maximum number of items to be processed at a time - - #endregion parameter data - - #region Command code - /// - /// Get connection options. - /// - internal ConnectionOptions GetConnectionOption() - { - ConnectionOptions options; - options = new ConnectionOptions(); - options.Authentication = this.Authentication; - options.Locale = this.Locale; - options.Authority = this.Authority; - options.EnablePrivileges = this.EnableAllPrivileges; - options.Impersonation = this.Impersonation; - if (this.Credential != null) - { - if (!(this.Credential.UserName == null && this.Credential.Password == null)) // Empty credential, use implicit credential - { - options.Username = this.Credential.UserName; - options.SecurePassword = this.Credential.Password; - } - } - - return options; - } - /// - /// Set wmi instance helper. - /// - internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) - { - ConnectionOptions options = GetConnectionOption(); - ManagementObject mObject = null; - var setObject = this as SetWmiInstance; - if (setObject != null) - { - if (setObject.Path != null) - { - mPath.Server = serverName; - ManagementScope mScope = new ManagementScope(mPath, options); - if (mPath.IsClass) - { - ManagementClass mClass = new ManagementClass(mPath); - mClass.Scope = mScope; - mObject = mClass.CreateInstance(); - } - else - { - // This can throw if path does not exist caller should catch it. - ManagementObject mInstance = new ManagementObject(mPath); - mInstance.Scope = mScope; - try - { - mInstance.Get(); - } - catch (ManagementException e) - { - if (e.ErrorCode != ManagementStatus.NotFound) - { - throw; - } - - int namespaceIndex = setObject.Path.IndexOf(':'); - if (namespaceIndex == -1) - { - throw; - } - - int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); - if (classIndex == -1) - { - throw; - } - // Get class object and create instance. - string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); - ManagementPath classPath = new ManagementPath(newPath); - ManagementClass mClass = new ManagementClass(classPath); - mClass.Scope = mScope; - mInstance = mClass.CreateInstance(); - } - - mObject = mInstance; - } - } - else - { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(serverName, setObject.Namespace), options); - ManagementClass mClass = new ManagementClass(setObject.Class); - mClass.Scope = scope; - mObject = mClass.CreateInstance(); - } - - if (setObject.Arguments != null) - { - IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - mObject[en.Key as string] = en.Value; - } - } - } - - return mObject; - } - /// - /// Set wmi instance helper for building management path. - /// - internal ManagementPath SetWmiInstanceBuildManagementPath() - { - ManagementPath mPath = null; - var wmiInstance = this as SetWmiInstance; - if (wmiInstance != null) - { - // If Class is specified only CreateOnly flag is supported - if (wmiInstance.Class != null) - { - if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) - { - // Throw Terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "CreateOnlyFlagNotSpecifiedWithClassPath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); - } - - wmiInstance.PutType = PutType.CreateOnly; - } - else - { - mPath = new ManagementPath(wmiInstance.Path); - if (string.IsNullOrEmpty(mPath.NamespacePath)) - { - mPath.NamespacePath = wmiInstance.Namespace; - } - else if (wmiInstance.namespaceSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "NamespaceSpecifiedWithPath", - ErrorCategory.InvalidOperation, - wmiInstance.Namespace)); - } - - if (mPath.Server != "." && wmiInstance.serverNameSpecified) - { - // ThrowTerminatingError - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "ComputerNameSpecifiedWithPath", - ErrorCategory.InvalidOperation, - wmiInstance.ComputerName)); - } - - if (mPath.IsClass) - { - if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) - { - // Throw Terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "CreateOnlyFlagNotSpecifiedWithClassPath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); - } - - wmiInstance.PutType = PutType.CreateOnly; - } - else - { - if (wmiInstance.flagSpecified) - { - if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) - { - // Throw terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "NonUpdateFlagSpecifiedWithInstancePath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); - } - } - else - { - wmiInstance.PutType = PutType.UpdateOrCreate; - } - } - } - } - - return mPath; - } - - /// - /// Set wmi instance helper for pipeline input. - /// - internal ManagementObject SetWmiInstanceGetPipelineObject() - { - // Should only be called from Set-WMIInstance cmdlet - ManagementObject mObj = null; - var wmiInstance = this as SetWmiInstance; - if (wmiInstance != null) - { - // Extra check - if (wmiInstance.InputObject != null) - { - if (wmiInstance.InputObject.GetType() == typeof(ManagementClass)) - { - // Check if Flag specified is CreateOnly or not - if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) - { - // Throw terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "CreateOnlyFlagNotSpecifiedWithClassPath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); - } - - mObj = ((ManagementClass)wmiInstance.InputObject).CreateInstance(); - wmiInstance.PutType = PutType.CreateOnly; - } - else - { - // Check if Flag specified is Updateonly or UpdateOrCreateOnly or not - if (wmiInstance.flagSpecified) - { - if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) - { - // Throw terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "NonUpdateFlagSpecifiedWithInstancePath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); - } - } - else - { - wmiInstance.PutType = PutType.UpdateOrCreate; - } - - mObj = (ManagementObject)wmiInstance.InputObject.Clone(); - } - - if (wmiInstance.Arguments != null) - { - IDictionaryEnumerator en = wmiInstance.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - mObj[en.Key as string] = en.Value; - } - } - } - } - - return mObj; - } - - /// - /// Start this cmdlet as a WMI job... - /// - internal void RunAsJob(string cmdletName) - { - PSWmiJob wmiJob = new PSWmiJob(this, ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation)); - if (_context != null) - { - ((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob); - } - - WriteObject(wmiJob); - } - // Get the PowerShell execution context if it's available at cmdlet creation time... - private System.Management.Automation.ExecutionContext _context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - - #endregion Command code - } - /// - /// A class to perform async operations for WMI cmdlets. - /// - - internal class PSWmiJob : Job - { - #region internal constructor - - /// - ///Internal constructor for initializing WMI jobs. - /// - internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimt, string command) - : base(command, null) - { - PSJobTypeName = WMIJobType; - _throttleManager.ThrottleLimit = throttleLimt; - for (int i = 0; i < computerName.Length; i++) - { - PSWmiChildJob job = new PSWmiChildJob(cmds, computerName[i], _throttleManager); - job.StateChanged += new EventHandler(HandleChildJobStateChanged); - job.JobUnblocked += new EventHandler(HandleJobUnblocked); - ChildJobs.Add(job); - } - - CommonInit(throttleLimt); - } - - /// - /// Internal constructor for initializing WMI jobs, where WMI command is executed a variable - /// number of times. - /// - internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimit, string command, int count) - : base(command, null) - { - PSJobTypeName = WMIJobType; - _throttleManager.ThrottleLimit = throttleLimit; - for (int i = 0; i < computerName.Length; ++i) - { - PSWmiChildJob childJob = new PSWmiChildJob(cmds, computerName[i], _throttleManager, count); - childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); - childJob.JobUnblocked += new EventHandler(HandleJobUnblocked); - ChildJobs.Add(childJob); - } - - CommonInit(throttleLimit); - } - - #endregion internal constructor - - // Set to true when at least one chil job failed - private bool _atleastOneChildJobFailed = false; - - // Count the number of childs which have finished - private int _finishedChildJobsCount = 0; - - // Count of number of child jobs which are blocked - private int _blockedChildJobsCount = 0; - - // WMI Job type name. - private const string WMIJobType = "WmiJob"; - - /// - /// Handles the StateChanged event from each of the child job objects. - /// - /// - /// - private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) - { - if (e.JobStateInfo.State == JobState.Blocked) - { - // increment count of blocked child jobs - lock (_syncObject) - { - _blockedChildJobsCount++; - } - // if any of the child job is blocked, we set state to blocked - SetJobState(JobState.Blocked, null); - return; - } - - // Ignore state changes which are not resulting in state change to finished. - if ((!IsFinishedState(e.JobStateInfo.State)) || (e.JobStateInfo.State == JobState.NotStarted)) - { - return; - } - - if (e.JobStateInfo.State == JobState.Failed) - { - // If any of the child job failed, we set status to failed - _atleastOneChildJobFailed = true; - } - - bool allChildJobsFinished = false; - lock (_syncObject) - { - _finishedChildJobsCount++; - - // We are done - if (_finishedChildJobsCount == ChildJobs.Count) - { - allChildJobsFinished = true; - } - } - - if (allChildJobsFinished) - { - // if any child job failed, set status to failed - // If stop was called set, status to stopped - // else completed - if (_atleastOneChildJobFailed) - { - SetJobState(JobState.Failed); - } - else if (_stopIsCalled == true) - { - SetJobState(JobState.Stopped); - } - else - { - SetJobState(JobState.Completed); - } - } - } - - private bool _stopIsCalled = false; - private string _statusMessage; - /// - /// Message indicating status of the job. - /// - public override string StatusMessage - { - get - { - return _statusMessage; - } - } - // ISSUE: Implement StatusMessage - /// - /// Checks the status of remote command execution. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - private void SetStatusMessage() - { - _statusMessage = "test"; - } - - private bool _moreData = false; - /// - /// Indicates if more data is available. - /// - /// - /// This has more data if any of the child jobs have more data. - /// - public override bool HasMoreData - { - get - { - // moreData is set to false and will be set to true - // if at least one child is has more data. - - // if ( (!moreData)) - // { - bool atleastOneChildHasMoreData = false; - - for (int i = 0; i < ChildJobs.Count; i++) - { - if (ChildJobs[i].HasMoreData) - { - atleastOneChildHasMoreData = true; - break; - } - } - - _moreData = atleastOneChildHasMoreData; - // } - - return _moreData; - } - } - - /// - /// Computers on which this job is running. - /// - public override string Location - { - get - { - return ConstructLocation(); - } - } - - private string ConstructLocation() - { - StringBuilder location = new StringBuilder(); - - foreach (PSWmiChildJob job in ChildJobs) - { - location.Append(job.Location); - location.Append(','); - } - - location.Remove(location.Length - 1, 1); - - return location.ToString(); - } - /// - /// Stop Job. - /// - public override void StopJob() - { - // AssertNotDisposed(); - - if (!IsFinishedState(JobStateInfo.State)) - { - _stopIsCalled = true; - - _throttleManager.StopAllOperations(); - - Finished.WaitOne(); - } - } - /// - /// Release all the resources. - /// - /// - /// if true, release all the managed objects. - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (!_isDisposed) - { - _isDisposed = true; - try - { - if (!IsFinishedState(JobStateInfo.State)) - { - StopJob(); - } - - _throttleManager.Dispose(); - foreach (Job job in ChildJobs) - { - job.Dispose(); - } - } - finally - { - base.Dispose(disposing); - } - } - } - } - - private bool _isDisposed = false; - /// - /// Initialization common to both constructors. - /// - private void CommonInit(int throttleLimit) - { - // Since no results are produced by any streams. We should - // close all the streams - base.CloseAllStreams(); - - // set status to "in progress" - SetJobState(JobState.Running); - - // submit operations to the throttle manager - _throttleManager.EndSubmitOperations(); - } - /// - /// Handles JobUnblocked event from a child job and decrements - /// count of blocked child jobs. When count reaches 0, sets the - /// state of the parent job to running. - /// - /// Sender of this event, unused. - /// event arguments, should be empty in this - /// case - private void HandleJobUnblocked(object sender, EventArgs eventArgs) - { - bool unblockjob = false; - - lock (_syncObject) - { - _blockedChildJobsCount--; - - if (_blockedChildJobsCount == 0) - { - unblockjob = true; - } - } - - if (unblockjob) - { - SetJobState(JobState.Running, null); - } - } - - private ThrottleManager _throttleManager = new ThrottleManager(); - - private object _syncObject = new object(); // sync object - } - - /// - /// Class for WmiChildJob object. This job object Execute wmi cmdlet. - /// - internal class PSWmiChildJob : Job - { - #region internal constructor - - /// - /// Internal constructor for initializing WMI jobs. - /// - internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager) - : base(null, null) - { - UsesResultsCollection = true; - Location = computerName; - _throttleManager = throttleManager; - _wmiSinkArray = new ArrayList(); - ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - _wmiSinkArray.Add(wmiSink); - _sinkCompleted++; - wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); - wmiSink.Completed += new CompletedEventHandler(this.JobDone); - _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink); - _helper.WmiOperationState += new EventHandler(HandleWMIState); - _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); - SetJobState(JobState.NotStarted); - IThrottleOperation operation = _helper; - operation.OperationComplete += new EventHandler(HandleOperationComplete); - throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); - throttleManager.AddOperation(operation); - } - - /// - /// Internal constructor for initializing WMI jobs, where WMI command is executed a variable - /// number of times. - /// - internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager, int count) - : base(null, null) - { - UsesResultsCollection = true; - Location = computerName; - _throttleManager = throttleManager; - _wmiSinkArray = new ArrayList(); - ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - _wmiSinkArray.Add(wmiSink); - _sinkCompleted += count; - wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); - wmiSink.Completed += new CompletedEventHandler(this.JobDone); - _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count); - _helper.WmiOperationState += new EventHandler(HandleWMIState); - _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); - SetJobState(JobState.NotStarted); - IThrottleOperation operation = _helper; - operation.OperationComplete += new EventHandler(HandleOperationComplete); - throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); - throttleManager.AddOperation(operation); - } - - #endregion internal constructor - - private WmiAsyncCmdletHelper _helper; - // bool _bFinished; - private ThrottleManager _throttleManager; - private object _syncObject = new object(); // sync object - private int _sinkCompleted; - private bool _bJobFailed; - private bool _bAtLeastOneObject; - - private ArrayList _wmiSinkArray; - /// - /// Event raised by this job to indicate to its parent that - /// its now unblocked by the user. - /// - internal event EventHandler JobUnblocked; - - /// - /// Set the state of the current job from blocked to - /// running and raise an event indicating to this - /// parent job that this job is unblocked. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal void UnblockJob() - { - SetJobState(JobState.Running, null); - JobUnblocked.SafeInvoke(this, EventArgs.Empty); - } - - internal ManagementOperationObserver GetNewSink() - { - ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - _wmiSinkArray.Add(wmiSink); - lock (_syncObject) - { - _sinkCompleted++; - } - - wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); - wmiSink.Completed += new CompletedEventHandler(this.JobDone); - return wmiSink; - } - - /// - /// It receives Management objects. - /// - private void NewObject(object sender, ObjectReadyEventArgs obj) - { - if (!_bAtLeastOneObject) - { - _bAtLeastOneObject = true; - } - - this.WriteObject(obj.NewObject); - } - - /// - /// It is called when WMI job is done. - /// - private void JobDone(object sender, CompletedEventArgs obj) - { - lock (_syncObject) - { - _sinkCompleted--; - } - - if (obj.Status != ManagementStatus.NoError) - { - _bJobFailed = true; - } - - if (_sinkCompleted == 0) - { - // Notify throttle manager and change the state to complete - // Two cases where _bFinished should be set to false. - // 1) Invalid class or some other condition so that after making a connection WMI is throwing an error - // 2) We could not get any instance for the class. - /*if(bAtLeastOneObject ) - _bFinished = true;*/ - _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); - if (!_bJobFailed) - { - _helper.State = WmiState.Completed; - SetJobState(JobState.Completed); - } - else - { - _helper.State = WmiState.Failed; - SetJobState(JobState.Failed); - } - } - } - - /// - /// It is called when the call to Win32shutdown is successfully completed. - /// - private void JobDoneForWin32Shutdown(object sender, EventArgs arg) - { - lock (_syncObject) - { - _sinkCompleted--; - } - - if (_sinkCompleted == 0) - { - _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); - _helper.State = WmiState.Completed; - SetJobState(JobState.Completed); - } - } - - /// - /// Message indicating status of the job. - /// - public override string StatusMessage { get; } = "test"; - - /// - /// Indicates if there is more data available in - /// this Job. - /// - public override bool HasMoreData - { - get - { - return (Results.IsOpen || Results.Count > 0); - } - } - - /// - /// Returns the computer on which this command is - /// running. - /// - public override string Location { get; } - - /// - /// Stops the job. - /// - public override void StopJob() - { - AssertNotDisposed(); - _throttleManager.StopOperation(_helper); - - // if IgnoreStop is set, then StopOperation will - // return immediately, but StopJob should only - // return when job is complete. Waiting on the - // wait handle will ensure that its blocked - // until the job reaches a terminal state - Finished.WaitOne(); - } - - /// - /// Release all the resources. - /// - /// - /// if true, release all the managed objects. - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (!_isDisposed) - { - _isDisposed = true; - base.Dispose(disposing); - } - } - } - - private bool _isDisposed; - - /// - /// Handles operation complete event. - /// - private void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) - { - WmiAsyncCmdletHelper helper = (WmiAsyncCmdletHelper)sender; - - if (helper.State == WmiState.NotStarted) - { - // This is a case WMI operation was not started. - SetJobState(JobState.Stopped, helper.InternalException); - } - else if (helper.State == WmiState.Running) - { - SetJobState(JobState.Running, helper.InternalException); - } - else if (helper.State == WmiState.Completed) - { - SetJobState(JobState.Completed, helper.InternalException); - } - else if (helper.State == WmiState.Failed) - { - SetJobState(JobState.Failed, helper.InternalException); - } - else - { - SetJobState(JobState.Stopped, helper.InternalException); - } - } - /// - /// Handles WMI state changed. - /// - private void HandleWMIState(object sender, WmiJobStateEventArgs stateEventArgs) - { - if (stateEventArgs.WmiState == WmiState.Running) - { - SetJobState(JobState.Running, _helper.InternalException); - } - else if (stateEventArgs.WmiState == WmiState.NotStarted) - { - SetJobState(JobState.NotStarted, _helper.InternalException); - } - else if (stateEventArgs.WmiState == WmiState.Completed) - { - SetJobState(JobState.Completed); - } - else if (stateEventArgs.WmiState == WmiState.Failed) - { - SetJobState(JobState.Failed, _helper.InternalException); - } - else - { - SetJobState(JobState.Stopped, _helper.InternalException); - } - } - - /// - /// Handle a throttle complete event. - /// - /// Sender of this event. - /// Not used in this method. - private void HandleThrottleComplete(object sender, EventArgs eventArgs) - { - if (_helper.State == WmiState.NotStarted) - { - // This is a case WMI operation was not started. - SetJobState(JobState.Stopped, _helper.InternalException); - } - else if (_helper.State == WmiState.Running) - { - SetJobState(JobState.Running, _helper.InternalException); - } - else if (_helper.State == WmiState.Completed) - { - SetJobState(JobState.Completed, _helper.InternalException); - } - else if (_helper.State == WmiState.Failed) - { - SetJobState(JobState.Failed, _helper.InternalException); - } - else - { - SetJobState(JobState.Stopped, _helper.InternalException); - } - // Do Nothing - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs deleted file mode 100644 index 3f91d597e57..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.CodeDom; -using System.CodeDom.Compiler; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.IO; -using System.Management; -using System.Management.Automation; -using System.Net; -using System.Reflection; -using System.Resources; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Web.Services; -using System.Web.Services.Description; -using System.Web.Services.Discovery; -using System.Xml; - -using Microsoft.CSharp; -using Microsoft.Win32; - -using Dbg = System.Management.Automation; - -namespace Microsoft.PowerShell.Commands -{ - #region New-WebServiceProxy - - /// - /// Cmdlet for new-WebService Proxy. - /// - [Cmdlet(VerbsCommon.New, "WebServiceProxy", DefaultParameterSetName = "NoCredentials", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135238")] - public sealed class NewWebServiceProxy : PSCmdlet - { - #region Parameters - - /// - /// URI of the web service. - /// - [Parameter(Mandatory = true, Position = 0)] - [ValidateNotNullOrEmpty] - [Alias("WL", "WSDL", "Path")] - public System.Uri Uri - { - get { return _uri; } - - set - { - _uri = value; - } - } - - private System.Uri _uri; - - /// - /// Parameter Class name. - /// - [Parameter(Position = 1)] - [ValidateNotNullOrEmpty] - [Alias("FileName", "FN")] - public string Class - { - get { return _class; } - - set - { - _class = value; - } - } - - private string _class; - - /// - /// Namespace. - /// - [Parameter(Position = 2)] - [ValidateNotNullOrEmpty] - [Alias("NS")] - public string Namespace - { - get { return _namespace; } - - set - { - _namespace = value; - } - } - - private string _namespace; - - /// - /// Credential. - /// - [Parameter(ParameterSetName = "Credential")] - [ValidateNotNullOrEmpty] - [Credential] - [Alias("Cred")] - public PSCredential Credential - { - get { return _credential; } - - set - { - _credential = value; - } - } - - private PSCredential _credential; - - /// - /// Use default credential.. - /// - [Parameter(ParameterSetName = "UseDefaultCredential")] - [ValidateNotNull] - [Alias("UDC")] - public SwitchParameter UseDefaultCredential - { - get { return _usedefaultcredential; } - - set - { - _usedefaultcredential = value; - } - } - - private SwitchParameter _usedefaultcredential; - - #endregion - - #region overrides - /// - /// Cache for storing URIs. - /// - private static Dictionary s_uriCache = new Dictionary(); - - /// - /// Cache for storing sourcecodehashes. - /// - private static Dictionary s_srccodeCache = new Dictionary(); - - /// - /// Holds the hash code of the source generated. - /// - private int _sourceHash; - /// - /// Random class. - /// - - private object _cachelock = new object(); - private static Random s_rnd = new Random(); - /// - /// BeginProcessing code. - /// - protected override void BeginProcessing() - { - if (string.IsNullOrWhiteSpace(_uri.ToString())) - { - Exception ex = new ArgumentException(WebServiceResources.InvalidUri); - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null); - ThrowTerminatingError(er); - } - // check if system.web is available.This assembly is not available in win server core. - string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; - try - { - Assembly webAssembly = Assembly.Load(AssemblyString); - } - catch (FileNotFoundException ex) - { - ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null); - er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported); - ThrowTerminatingError(er); - } - - int sourceCache = 0; - - lock (s_uriCache) - { - if (s_uriCache.ContainsKey(_uri)) - { - // if uri is present in the cache - string ns; - s_uriCache.TryGetValue(_uri, out ns); - string[] data = ns.Split('|'); - if (string.IsNullOrEmpty(_namespace)) - { - if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase)) - { - _namespace = data[0]; - _class = data[1]; - } - } - - sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture); - } - } - - if (string.IsNullOrEmpty(_namespace)) - { - _namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName(); - } - // if class is null,generate a name for it - if (string.IsNullOrEmpty(_class)) - { - _class = "MyClass" + GenerateRandomName(); - } - - Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class); - if (webserviceproxy == null) - return; - object instance = InstantiateWebServiceProxy(webserviceproxy); - - // to set the credentials into the generated webproxy Object - PropertyInfo[] pinfo = instance.GetType().GetProperties(); - foreach (PropertyInfo pr in pinfo) - { - if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase)) - { - if (UseDefaultCredential.IsPresent) - { - bool flag = true; - pr.SetValue(instance, flag as object, null); - } - } - - if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase)) - { - if (Credential != null) - { - NetworkCredential cred = Credential.GetNetworkCredential(); - pr.SetValue(instance, cred as object, null); - } - } - } - - // disposing the entries in a cache - // Adding to Cache - lock (s_uriCache) - { - s_uriCache.Remove(_uri); - } - - if (sourceCache > 0) - { - lock (_cachelock) - { - s_srccodeCache.Remove(sourceCache); - } - } - - string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) }); - lock (s_uriCache) - { - s_uriCache.Add(_uri, key); - } - - lock (_cachelock) - { - s_srccodeCache.Add(_sourceHash, instance); - } - - WriteObject(instance, true); - } - - #endregion - - #region private - - private static ulong s_sequenceNumber = 1; - private static object s_sequenceNumberLock = new object(); - - /// - /// Generates a random name. - /// - /// String. - private string GenerateRandomName() - { - string rndname = null; - string givenuri = _uri.ToString(); - for (int i = 0; i < givenuri.Length; i++) - { - Int32 val = System.Convert.ToInt32(givenuri[i], CultureInfo.InvariantCulture); - if ((val >= 65 && val <= 90) || (val >= 48 && val <= 57) || (val >= 97 && val <= 122)) - { - rndname += givenuri[i]; - } - else - { - rndname += "_"; - } - } - - string sequenceString; - lock (s_sequenceNumberLock) - { - sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture); - } - - if (rndname.Length > 30) - { - return (sequenceString + rndname.Substring(rndname.Length - 30)); - } - - return (sequenceString + rndname); - } - - /// - /// Generates the Assembly. - /// - /// - /// - /// - [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] - private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName) - { - DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); - - // if paramset is defaultcredential, set the flag in wcclient - if (_usedefaultcredential.IsPresent) - dcp.UseDefaultCredentials = true; - - // if paramset is credential, assign the credentials - if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase)) - dcp.Credentials = _credential.GetNetworkCredential(); - - try - { - dcp.AllowAutoRedirect = true; - dcp.DiscoverAny(_uri.ToString()); - dcp.ResolveAll(); - } - catch (WebException ex) - { - ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri); - if (ex.InnerException != null) - er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); - WriteError(er); - return null; - } - catch (InvalidOperationException ex) - { - ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri); - WriteError(er); - return null; - } - - // create the namespace - CodeNamespace codeNS = new CodeNamespace(); - if (!string.IsNullOrEmpty(NameSpace)) - codeNS.Name = NameSpace; - - // create the class and add it to the namespace - if (!string.IsNullOrEmpty(ClassName)) - { - CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); - codeClass.IsClass = true; - codeClass.Attributes = MemberAttributes.Public; - codeNS.Types.Add(codeClass); - } - - // create a web reference to the uri docs - WebReference wref = new WebReference(dcp.Documents, codeNS); - WebReferenceCollection wrefs = new WebReferenceCollection(); - wrefs.Add(wref); - - // create a codecompileunit and add the namespace to it - CodeCompileUnit codecompileunit = new CodeCompileUnit(); - codecompileunit.Namespaces.Add(codeNS); - - WebReferenceOptions wrefOptions = new WebReferenceOptions(); - wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; - wrefOptions.Verbose = true; - - // create a csharpprovider and compile it - CSharpCodeProvider csharpprovider = new CSharpCodeProvider(); - StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions); - - StringBuilder codegenerator = new StringBuilder(); - StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture); - try - { - csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null); - } - catch (NotImplementedException ex) - { - ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); - WriteError(er); - } - // generate the hashcode of the CodeCompileUnit - _sourceHash = codegenerator.ToString().GetHashCode(); - - // if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so - // return the instance of th eproxy in the cache - if (s_srccodeCache.ContainsKey(_sourceHash)) - { - object obj; - s_srccodeCache.TryGetValue(_sourceHash, out obj); - WriteObject(obj, true); - return null; - } - - CompilerParameters options = new CompilerParameters(); - CompilerResults results = null; - - foreach (string warning in Warnings) - { - this.WriteWarning(warning); - } - - // add the references to the required assemblies - options.ReferencedAssemblies.Add("System.dll"); - options.ReferencedAssemblies.Add("System.Data.dll"); - options.ReferencedAssemblies.Add("System.Xml.dll"); - options.ReferencedAssemblies.Add("System.Web.Services.dll"); - options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); - GetReferencedAssemblies(typeof(Cmdlet).Assembly, options); - options.GenerateInMemory = true; - options.TreatWarningsAsErrors = false; - options.WarningLevel = 4; - options.GenerateExecutable = false; - try - { - results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString()); - } - catch (NotImplementedException ex) - { - ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri); - WriteError(er); - } - - return results.CompiledAssembly; - } - - /// - /// Function to add all the assemblies required to generate the web proxy. - /// - /// - /// - private void GetReferencedAssemblies(Assembly assembly, CompilerParameters parameters) - { - if (!parameters.ReferencedAssemblies.Contains(assembly.Location)) - { - string location = Path.GetFileName(assembly.Location); - if (!parameters.ReferencedAssemblies.Contains(location)) - { - parameters.ReferencedAssemblies.Add(assembly.Location); - foreach (AssemblyName referencedAssembly in assembly.GetReferencedAssemblies()) - GetReferencedAssemblies(Assembly.Load(referencedAssembly.FullName), parameters); - } - } - } - /// - /// Instantiates the object - /// if a type of WebServiceBindingAttribute is not found, throw an exception. - /// - /// - /// - private object InstantiateWebServiceProxy(Assembly assembly) - { - Type proxyType = null; - // loop through the types of the assembly and identify the type having - // a web service binding attribute - foreach (Type type in assembly.GetTypes()) - { - object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); - if (obj.Length > 0) - { - proxyType = type; - break; - } - - if (proxyType != null) - { - break; - } - } - - System.Management.Automation.Diagnostics.Assert( - proxyType != null, - "Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)"); - - return assembly.CreateInstance(proxyType.ToString()); - } - - #endregion - } - #endregion -} diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx deleted file mode 100644 index 077beaa117f..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The {0} cmdlet is not supported on this version of Windows. - - - Cannot find any Control Panel item with the given canonical name {0}. - - - Cannot find any control panel item with the given canonical name {0} that satisfies the specified category. - - - Cannot find any control panel item with the given category {0}. - - - Cannot find the Control Panel item based on the given instance of type {0}. - - - Cannot find any control panel item with the given name {0}. - - - Cannot find any Control Panel item with the given name {0} that satisfies the specified category. - - - Cannot find any control panel item that has a canonical name. - - - Cannot find any Control Panel item that satisfies the specified category and has a canonical name. - - - &Open - - diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx deleted file mode 100644 index cee97f4adae..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Log "{0}" could not be read to completion due to the following error. This may have occurred because the log was cleared while still being read. {1} - - - No matches found - - - Do you want to clear the "{0}" log on the computer "{1}"? - - - The Log name "{0}" does not exist in the computer "{1}". - - - The path to the "{1}" computer cannot be found. - - - The source name "{2}" does not exist on computer "{1}". - - - The registry key for the log "{0}" for source "{2}" could not be opened. - - - The operating system reported an error when writing the event entry to the event log. A Windows error code is not available. - - - Do you want to change the properties of the "{0}" log on the "{1}" computer? - - - The registry key for the log "{0}" could not be opened on the computer "{1}". - - - The value supplied for MaximumSize parameter has to be in the range of 64 KB to 4GB with an increment of 64 KB. Please enter a proper value and then retry. - - - Access to the "{1}" computer is denied. - - - The "{2}" source is already registered with the "{0}" log. - - - The "{2}" source is already registered on the "{1}" computer. - - - Do you want to remove the "{0}" log from the "{1}" computer? - - - Do you want to remove the "{0}" source from the "{1}" computer? - - - Retention days is valid only if the overflow action is "OverwriteOlder". Please change and try again. - - - Specify a valid value for the number of retention days. - - - Access is denied. Try running the command again in a session that has been opened with elevated user rights (that is, Run as Administrator). - - - The command is not supported in this version of the operating system. - - diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx deleted file mode 100644 index 73de4f80a24..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - This PowerShell Snap-In contains management cmdlets that are used to manage Windows components. - - - Microsoft Corporation - - - Management PSSnapIn - - diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx deleted file mode 100644 index 9d92573d86d..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Cannot use transaction. The transaction has timed out. - - diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx deleted file mode 100644 index 91d57c51902..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The Uniform Resource Identifier (URI) cannot be null or empty. Provide a valid URI. - - - The command is not supported on this operating system. - - diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx deleted file mode 100644 index 47f736405ea..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Could not register for event. The class name is invalid. Valid class names consist of letters, digits and the underscore character. - - - Could not get objects from namespace {0}. {1} - - - The class name {0} is invalid. Valid class names consist of letters, digits, '_', '?', '*', '-' and "[]". - - - {0} ({1}) - - - Parameter {0} should be specified to compose the query. - - - {0}"{1}" - - diff --git a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs deleted file mode 100644 index ed3495dd334..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// PSManagementPSSnapIn is a class for facilitating registry - /// of necessary information for PowerShell management PSSnapin. - /// - /// This class will be built with monad management dll. - /// - [RunInstaller(true)] - public sealed class PSManagementPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSManagementPSSnapIn() - : base() - { - } - - /// - /// Get name of this PSSnapin. - /// - public override string Name - { - get - { - return RegistryStrings.ManagementMshSnapinName; - } - } - - /// - /// Get the default vendor string for this PSSnapin. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. - /// - public override string VendorResource - { - get - { - return "ManagementMshSnapInResources,Vendor"; - } - } - - /// - /// Get the default description string for this PSSnapin. - /// - public override string Description - { - get - { - return "This PSSnapIn contains general management cmdlets used to manage Windows components."; - } - } - - /// - /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. - /// - public override string DescriptionResource - { - get - { - return "ManagementMshSnapInResources,Description"; - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 6b893ccbfec..46affc17cb9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -16,21 +16,6 @@ $(DefineConstants);CORECLR - - - - - - - - - - - - - - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx deleted file mode 100644 index ae0b785d645..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The supplied template was invalid: {0}. For more information on the template syntax, type 'Get-Help ConvertFrom-String' - - - No input was supplied - - - {0} is not a valid Regular Expression delimiter - - - One or more PropertyNames are invalid - - - Template file path resolves to more than one file. Specify a path to a single file - - - ConvertFrom-String appears to be having trouble parsing your data using the template you've provided. We'd love to take a look at what went wrong, if you'd like to share the data and template used to parse it. We've saved these files to {0} and {1} - feel free to attach them in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. - - - ConvertFrom-String appears to be having trouble parsing your data using the template you've provided. We'd love to take a look at what went wrong, if you'd like to share the data and template used to parse it. We've saved these files to {0} and {1} - feel free to attach them in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. - - - Error converting string value to specified type at file character position {0} - - - Template file is required for UpdateTemplate parameter - - - Template file was not found - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx deleted file mode 100644 index 9e65acdc23c..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Text examples must follow the pattern "input value = output value" - - - PSObject examples should have 'Before' and 'After' properties - - - Convert-String appears to be having trouble parsing your data using the examples you've provided. We'd love to take a look at what went wrong - feel free to send the command you tried in a mail to psdmfb@microsoft.com. We will review all submissions, although we can't guarantee a response. - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx deleted file mode 100644 index 824b56ec6bf..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - There are two instances of non-sequence Property '{0}' at {1} and {2} in parent Span {3} - - - Property '{0}' at {1} has no value and is not optional or a containing span - - - No program can be found for the given input - - - Internal error: Property cannot be null - - - Unexpected Span ending bracket found at {0} - - - Missing Span value at {0} while processing {1} - - - Invalid format at {0} while processing {1} - - - Invalid type name '{0}' at {1} while processing {2} - - - Missing Span name at {0} while processing {1} - - - First character of a name must be a letter or underscore at {0} while processing {1} - - - Characters of a name must be letters, digits, or underscores at {0} while processing {1} - - - Cannot embed attribute suffixes (e.g. optional, sequence) in names at {0} while processing {1} - - - Cannot use reserved word '{2}' at {0} while processing {1} - - - Expected value indicator at {0} while processing {1} - - - Unable to convert string value to specified type while processing {0} - - - Unexpected EOF while processing {0} - - - Span starting at line {0} column {1} - - - Internal error: Property '{0}' at {1} has no containing parent - - - Property '{0}' definition at {1} is inconsistent with earlier definition(s) - - - Internal error: no parent region found. - - - Internal error: parent regions cannot be null or empty. - - - line {0} column {1} - - - at {0} - - - '{0}' - - - line {0} column {1} - - - No template text file start for Span {0} - - - Internal error: Property '{0}' not found - - - Internal error: Invalid parser operation - - - Cached program was not found in template file for property: {0} - - - Template text does not match cached programs - - - The template text contains no example to parse - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx deleted file mode 100644 index 71e978c89b4..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - An element with the same key but a different value already exists. Key: {0} - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx deleted file mode 100644 index 3bca38847db..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - This PowerShell snap-in contains utility cmdlets that are used to view and organize data in different ways. - - - Microsoft Corporation - - - PowerShell utility snap-in - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs deleted file mode 100644 index ebb3325d0b7..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// PSUtilityPSSnapIn is a class for facilitating registry - /// of necessary information for PowerShell utility PSSnapin. - /// - [RunInstaller(true)] - public sealed class PSUtilityPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSUtilityPSSnapIn() - : base() - { - } - - /// - /// Get name of this PSSnapin. - /// - public override string Name - { - get - { - return RegistryStrings.UtilityMshSnapinName; - } - } - - /// - /// Get the default vendor string for this PSSnapin. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. - /// - public override string VendorResource - { - get - { - return "UtilityMshSnapInResources,Vendor"; - } - } - - /// - /// Get the default description string for this PSSnapin. - /// - public override string Description - { - get - { - return "This PSSnapIn contains utility cmdlets used to manipulate data."; - } - } - - /// - /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. - /// - public override string DescriptionResource - { - get - { - return "UtilityMshSnapInResources,Description"; - } - } - } -} diff --git a/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj index bbc8023b1da..455089062e9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj +++ b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj @@ -18,12 +18,4 @@ - - - - - - - - diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx deleted file mode 100644 index 7cfdd2f63b5..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - This PowerShell snap-in contains cmdlets (such as Start-Transcript and Stop-Transcript) that are provided for use with the PowerShell console host. - - - Microsoft Corporation - - - Host PowerShell Snap-In. - - diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs deleted file mode 100644 index ec2b702a144..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Management.Automation; -using System.Reflection; - -namespace Microsoft.PowerShell -{ - /// - /// EngineInstaller is a class for facilitating registry of necessary - /// information for PowerShell engine. - /// - /// At install time, installation utilities (like InstallUtil.exe) will - /// call install this engine assembly based on the implementation in - /// this class. - /// - /// This class derives from base class PSInstaller. PSInstaller will - /// handle the details about how information got written into registry. - /// Here, the information about registry content is provided. - /// - [RunInstaller(true)] - public sealed class EngineInstaller : PSInstaller - { - /// - /// Constructor. - /// - public EngineInstaller() - : base() - { - } - - /// - /// - internal sealed override string RegKey - { - get - { - return RegistryStrings.MonadEngineKey; - } - } - - private static string EngineVersion - { - get - { - return PSVersionInfo.FeatureVersionString; - } - } - - private Dictionary _regValues = null; - /// - /// - internal sealed override Dictionary RegValues - { - get - { - if (_regValues == null) - { - _regValues = new Dictionary(); - _regValues[RegistryStrings.MonadEngine_MonadVersion] = EngineVersion; - _regValues[RegistryStrings.MonadEngine_ApplicationBase] = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - _regValues[RegistryStrings.MonadEngine_ConsoleHostAssemblyName] = Assembly.GetExecutingAssembly().FullName; - _regValues[RegistryStrings.MonadEngine_ConsoleHostModuleName] = Assembly.GetExecutingAssembly().Location; - _regValues[RegistryStrings.MonadEngine_RuntimeVersion] = Assembly.GetExecutingAssembly().ImageRuntimeVersion; - } - - return _regValues; - } - } - } -} diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs deleted file mode 100644 index e1132d75751..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// PSHostPSSnapIn is a class for facilitating registry - /// of necessary information for PowerShell host PSSnapin. - /// - [RunInstaller(true)] - public sealed class PSHostPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSHostPSSnapIn() - : base() - { - } - - /// - /// Get name of this PSSnapin. - /// - public override string Name - { - get - { - return RegistryStrings.HostMshSnapinName; - } - } - - /// - /// Get the default vendor string for this PSSnapin. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. - /// - public override string VendorResource - { - get - { - return "HostMshSnapInResources,Vendor"; - } - } - - /// - /// Get the default description string for this PSSnapin. - /// - public override string Description - { - get - { - return "This PSSnapIn contains cmdlets used by the MSH host."; - } - } - - /// - /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. - /// - public override string DescriptionResource - { - get - { - return "HostMshSnapInResources,Description"; - } - } - } -} diff --git a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj index a6dadabfed2..0747f57c821 100644 --- a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj +++ b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj @@ -10,11 +10,4 @@ - - - - - - - diff --git a/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx b/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx deleted file mode 100644 index e86df194720..00000000000 --- a/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - This PowerShell Snap-In contains cmdlets to manage PowerShell security. - - - Microsoft Corporation - - - Security PowerShell Snap-In. - - diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs deleted file mode 100644 index e92502e3911..00000000000 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Configuration.Install; -using System.IO; -using System.Management.Automation; -using System.Reflection; - -using Microsoft.Win32; - -namespace Microsoft.PowerShell -{ - /// - /// PSSecurityPSSnapIn is a class for facilitating registry - /// of necessary information for PowerShell security PSSnapin. - /// - [RunInstaller(true)] - public sealed class PSSecurityPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSSecurityPSSnapIn() - : base() - { - } - - /// - /// Get name of this PSSnapin. - /// - public override string Name - { - get - { - return RegistryStrings.SecurityMshSnapinName; - } - } - - /// - /// Get the default vendor string for this PSSnapin. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Get resource information for vendor. This is a string of format: resourceBaseName,resourceName. - /// - public override string VendorResource - { - get - { - return "SecurityMshSnapInResources,Vendor"; - } - } - - /// - /// Get the default description string for this PSSnapin. - /// - public override string Description - { - get - { - return "This PSSnapIn contains cmdlets to manage MSH security."; - } - } - - /// - /// Get resource information for description. This is a string of format: resourceBaseName,resourceName. - /// - public override string DescriptionResource - { - get - { - return "SecurityMshSnapInResources,Description"; - } - } - } -} diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 6227e1eaf24..579ab323a1f 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -17,8 +17,4 @@ $(DefineConstants);CORECLR - - - - diff --git a/src/Microsoft.WSMan.Management/WsManSnapin.cs b/src/Microsoft.WSMan.Management/WsManSnapin.cs deleted file mode 100644 index 4093caf12db..00000000000 --- a/src/Microsoft.WSMan.Management/WsManSnapin.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Management; -using System.Management.Automation; -using System.Runtime.InteropServices; -using System.Text; - -namespace Microsoft.WSMan.Management -{ - #region SnapIn - - /// - /// Create the PowerShell snap-in used to register the - /// WsManPSSnapIn cmdlets. Declaring the PSSnapIn class identifies - /// this .cs file as a PowerShell snap-in. - /// - [RunInstaller(true)] - public class WSManPSSnapIn : PSSnapIn - { - /// - /// Create an instance of the WsManSnapin class. - /// - public WSManPSSnapIn() - : base() - { - } - - /// - /// Specify the name of the PowerShell snap-in. - /// - public override string Name - { - get - { - return "WsManPSSnapIn"; - } - } - - /// - /// Specify the vendor for the PowerShell snap-in. - /// - public override string Vendor - { - get - { - return "Microsoft"; - } - } - - /// - /// Specify the localization resource information for the vendor. - /// Use the format: resourceBaseName,VendorName. - /// - public override string VendorResource - { - get - { - return "WsManPSSnapIn,Microsoft"; - } - } - - /// - /// Specify a description of the PowerShell snap-in. - /// - public override string Description - { - get - { - return "This is a PowerShell snap-in that includes the WsMan cmdlets."; - } - } - - /// - /// Specify the localization resource information for the description. - /// Use the format: resourceBaseName,Description. - /// - public override string DescriptionResource - { - get - { - return "WsManPSSnapIn,This is a PowerShell snap-in that includes the WsMan cmdlets."; - } - } - } - - #endregion SnapIn -} diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 753e58cd546..3160d220493 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -52,30 +52,8 @@ - - - - - - - - - - - - - - - - - - - - + - - - diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs deleted file mode 100644 index 7274c3bb954..00000000000 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs +++ /dev/null @@ -1,2239 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! -// -// This file has been generated -// by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// -// Generation timestamp: 10/21/2013 18:29:23 - -#pragma warning disable -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.17929 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// -// This source code was auto-generated by xsd, Version=4.0.30319.17929. -// - -namespace Microsoft.PowerShell.Cmdletization.Xml -{ - using System.Xml.Serialization; - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] - internal partial class PowerShellMetadata - { - private ClassMetadata _classField; - - private EnumMetadataEnum[] _enumsField; - - /// - public ClassMetadata Class - { - get - { - return this._classField; - } - - set - { - this._classField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)] - public EnumMetadataEnum[] Enums - { - get - { - return this._enumsField; - } - - set - { - this._enumsField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadata - { - private string _versionField; - - private string _defaultNounField; - - private ClassMetadataInstanceCmdlets _instanceCmdletsField; - - private StaticCmdletMetadata[] _staticCmdletsField; - - private ClassMetadataData[] _cmdletAdapterPrivateDataField; - - private string _cmdletAdapterField; - - private string _classNameField; - - private string _classVersionField; - - /// - public string Version - { - get - { - return this._versionField; - } - - set - { - this._versionField = value; - } - } - - /// - public string DefaultNoun - { - get - { - return this._defaultNounField; - } - - set - { - this._defaultNounField = value; - } - } - - /// - public ClassMetadataInstanceCmdlets InstanceCmdlets - { - get - { - return this._instanceCmdletsField; - } - - set - { - this._instanceCmdletsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)] - public StaticCmdletMetadata[] StaticCmdlets - { - get - { - return this._staticCmdletsField; - } - - set - { - this._staticCmdletsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)] - public ClassMetadataData[] CmdletAdapterPrivateData - { - get - { - return this._cmdletAdapterPrivateDataField; - } - - set - { - this._cmdletAdapterPrivateDataField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletAdapter - { - get - { - return this._cmdletAdapterField; - } - - set - { - this._cmdletAdapterField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassName - { - get - { - return this._classNameField; - } - - set - { - this._classNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassVersion - { - get - { - return this._classVersionField; - } - - set - { - this._classVersionField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadataInstanceCmdlets - { - private GetCmdletParameters _getCmdletParametersField; - - private GetCmdletMetadata _getCmdletField; - - private InstanceCmdletMetadata[] _cmdletField; - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - - /// - public GetCmdletMetadata GetCmdlet - { - get - { - return this._getCmdletField; - } - - set - { - this._getCmdletField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("Cmdlet")] - public InstanceCmdletMetadata[] Cmdlet - { - get - { - return this._cmdletField; - } - - set - { - this._cmdletField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class GetCmdletParameters - { - private PropertyMetadata[] _queryablePropertiesField; - - private Association[] _queryableAssociationsField; - - private QueryOption[] _queryOptionsField; - - private string _defaultCmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)] - public PropertyMetadata[] QueryableProperties - { - get - { - return this._queryablePropertiesField; - } - - set - { - this._queryablePropertiesField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] - public Association[] QueryableAssociations - { - get - { - return this._queryableAssociationsField; - } - - set - { - this._queryableAssociationsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)] - public QueryOption[] QueryOptions - { - get - { - return this._queryOptionsField; - } - - set - { - this._queryOptionsField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet - { - get - { - return this._defaultCmdletParameterSetField; - } - - set - { - this._defaultCmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class PropertyMetadata - { - private TypeMetadata _typeField; - - private PropertyQuery[] _itemsField; - - private ItemsChoiceType[] _itemsElementNameField; - - private string _propertyNameField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("ExcludeQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MaxValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MinValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("RegularQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")] - public PropertyQuery[] Items - { - get - { - return this._itemsField; - } - - set - { - this._itemsField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] - [System.Xml.Serialization.XmlIgnoreAttribute()] - public ItemsChoiceType[] ItemsElementName - { - get - { - return this._itemsElementNameField; - } - - set - { - this._itemsElementNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PropertyName - { - get - { - return this._propertyNameField; - } - - set - { - this._propertyNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class TypeMetadata - { - private string _pSTypeField; - - private string _eTSTypeField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSType - { - get - { - return this._pSTypeField; - } - - set - { - this._pSTypeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ETSType - { - get - { - return this._eTSTypeField; - } - - set - { - this._eTSTypeField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class Association - { - private AssociationAssociatedInstance _associatedInstanceField; - - private string _association1Field; - - private string _sourceRoleField; - - private string _resultRoleField; - - /// - public AssociationAssociatedInstance AssociatedInstance - { - get - { - return this._associatedInstanceField; - } - - set - { - this._associatedInstanceField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute("Association")] - public string Association1 - { - get - { - return this._association1Field; - } - - set - { - this._association1Field = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string SourceRole - { - get - { - return this._sourceRoleField; - } - - set - { - this._sourceRoleField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ResultRole - { - get - { - return this._resultRoleField; - } - - set - { - this._resultRoleField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class AssociationAssociatedInstance - { - private TypeMetadata _typeField; - - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter - { - private bool _errorOnNoMatchField; - - private bool _errorOnNoMatchFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ErrorOnNoMatch - { - get - { - return this._errorOnNoMatchField; - } - - set - { - this._errorOnNoMatchField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ErrorOnNoMatchSpecified - { - get - { - return this._errorOnNoMatchFieldSpecified; - } - - set - { - this._errorOnNoMatchFieldSpecified = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineField; - - private bool _valueFromPipelineFieldSpecified; - - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - private string[] _cmdletParameterSetsField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipeline - { - get - { - return this._valueFromPipelineField; - } - - set - { - this._valueFromPipelineField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified - { - get - { - return this._valueFromPipelineFieldSpecified; - } - - set - { - this._valueFromPipelineFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] CmdletParameterSets - { - get - { - return this._cmdletParameterSetsField; - } - - set - { - this._cmdletParameterSetsField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForInstanceMethodParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadata - { - private object _allowEmptyCollectionField; - - private object _allowEmptyStringField; - - private object _allowNullField; - - private object _validateNotNullField; - - private object _validateNotNullOrEmptyField; - - private CmdletParameterMetadataValidateCount _validateCountField; - - private CmdletParameterMetadataValidateLength _validateLengthField; - - private CmdletParameterMetadataValidateRange _validateRangeField; - - private string[] _validateSetField; - - private ObsoleteAttributeMetadata _obsoleteField; - - private bool _isMandatoryField; - - private bool _isMandatoryFieldSpecified; - - private string[] _aliasesField; - - private string _pSNameField; - - private string _positionField; - - /// - public object AllowEmptyCollection - { - get - { - return this._allowEmptyCollectionField; - } - - set - { - this._allowEmptyCollectionField = value; - } - } - - /// - public object AllowEmptyString - { - get - { - return this._allowEmptyStringField; - } - - set - { - this._allowEmptyStringField = value; - } - } - - /// - public object AllowNull - { - get - { - return this._allowNullField; - } - - set - { - this._allowNullField = value; - } - } - - /// - public object ValidateNotNull - { - get - { - return this._validateNotNullField; - } - - set - { - this._validateNotNullField = value; - } - } - - /// - public object ValidateNotNullOrEmpty - { - get - { - return this._validateNotNullOrEmptyField; - } - - set - { - this._validateNotNullOrEmptyField = value; - } - } - - /// - public CmdletParameterMetadataValidateCount ValidateCount - { - get - { - return this._validateCountField; - } - - set - { - this._validateCountField = value; - } - } - - /// - public CmdletParameterMetadataValidateLength ValidateLength - { - get - { - return this._validateLengthField; - } - - set - { - this._validateLengthField = value; - } - } - - /// - public CmdletParameterMetadataValidateRange ValidateRange - { - get - { - return this._validateRangeField; - } - - set - { - this._validateRangeField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)] - public string[] ValidateSet - { - get - { - return this._validateSetField; - } - - set - { - this._validateSetField = value; - } - } - - /// - public ObsoleteAttributeMetadata Obsolete - { - get - { - return this._obsoleteField; - } - - set - { - this._obsoleteField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool IsMandatory - { - get - { - return this._isMandatoryField; - } - - set - { - this._isMandatoryField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool IsMandatorySpecified - { - get - { - return this._isMandatoryFieldSpecified; - } - - set - { - this._isMandatoryFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases - { - get - { - return this._aliasesField; - } - - set - { - this._aliasesField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName - { - get - { - return this._pSNameField; - } - - set - { - this._pSNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Position - { - get - { - return this._positionField; - } - - set - { - this._positionField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateCount - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateLength - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateRange - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ObsoleteAttributeMetadata - { - private string _messageField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Message - { - get - { - return this._messageField; - } - - set - { - this._messageField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineField; - - private bool _valueFromPipelineFieldSpecified; - - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipeline - { - get - { - return this._valueFromPipelineField; - } - - set - { - this._valueFromPipelineField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified - { - get - { - return this._valueFromPipelineFieldSpecified; - } - - set - { - this._valueFromPipelineFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class QueryOption - { - private TypeMetadata _typeField; - - private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField; - - private string _optionNameField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string OptionName - { - get - { - return this._optionNameField; - } - - set - { - this._optionNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class GetCmdletMetadata - { - private CommonCmdletMetadata _cmdletMetadataField; - - private GetCmdletParameters _getCmdletParametersField; - - /// - public CommonCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonCmdletMetadata - { - private ObsoleteAttributeMetadata _obsoleteField; - - private string _verbField; - - private string _nounField; - - private string[] _aliasesField; - - private ConfirmImpact _confirmImpactField; - - private bool _confirmImpactFieldSpecified; - - private string _helpUriField; - - /// - public ObsoleteAttributeMetadata Obsolete - { - get - { - return this._obsoleteField; - } - - set - { - this._obsoleteField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Verb - { - get - { - return this._verbField; - } - - set - { - this._verbField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Noun - { - get - { - return this._nounField; - } - - set - { - this._nounField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases - { - get - { - return this._aliasesField; - } - - set - { - this._aliasesField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public ConfirmImpact ConfirmImpact - { - get - { - return this._confirmImpactField; - } - - set - { - this._confirmImpactField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ConfirmImpactSpecified - { - get - { - return this._confirmImpactFieldSpecified; - } - - set - { - this._confirmImpactFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")] - public string HelpUri - { - get - { - return this._helpUriField; - } - - set - { - this._helpUriField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - public enum ConfirmImpact - { - /// - None, - - /// - Low, - - /// - Medium, - - /// - High, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticCmdletMetadata - { - private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField; - - private StaticMethodMetadata[] _methodField; - - /// - public StaticCmdletMetadataCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("Method")] - public StaticMethodMetadata[] Method - { - get - { - return this._methodField; - } - - set - { - this._methodField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata - { - private string _defaultCmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet - { - get - { - return this._defaultCmdletParameterSetField; - } - - set - { - this._defaultCmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticMethodMetadata : CommonMethodMetadata - { - private StaticMethodParameterMetadata[] _parametersField; - - private string _cmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] - public StaticMethodParameterMetadata[] Parameters - { - get - { - return this._parametersField; - } - - set - { - this._parametersField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletParameterSet - { - get - { - return this._cmdletParameterSetField; - } - - set - { - this._cmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata - { - private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletOutputMetadata - { - private object _errorCodeField; - - private string _pSNameField; - - /// - public object ErrorCode - { - get - { - return this._errorCodeField; - } - - set - { - this._errorCodeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName - { - get - { - return this._pSNameField; - } - - set - { - this._pSNameField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodParameterMetadata - { - private TypeMetadata _typeField; - - private string _parameterNameField; - - private string _defaultValueField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ParameterName - { - get - { - return this._parameterNameField; - } - - set - { - this._parameterNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultValue - { - get - { - return this._defaultValueField; - } - - set - { - this._defaultValueField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata - { - private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodMetadata - { - private CommonMethodMetadataReturnValue _returnValueField; - - private string _methodNameField; - - /// - public CommonMethodMetadataReturnValue ReturnValue - { - get - { - return this._returnValueField; - } - - set - { - this._returnValueField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string MethodName - { - get - { - return this._methodNameField; - } - - set - { - this._methodNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodMetadataReturnValue - { - private TypeMetadata _typeField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceMethodMetadata : CommonMethodMetadata - { - private InstanceMethodParameterMetadata[] _parametersField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] - public InstanceMethodParameterMetadata[] Parameters - { - get - { - return this._parametersField; - } - - set - { - this._parametersField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceCmdletMetadata - { - private CommonCmdletMetadata _cmdletMetadataField; - - private InstanceMethodMetadata _methodField; - - private GetCmdletParameters _getCmdletParametersField; - - /// - public CommonCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - public InstanceMethodMetadata Method - { - get - { - return this._methodField; - } - - set - { - this._methodField = value; - } - } - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class PropertyQuery - { - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; - - /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class WildcardablePropertyQuery : PropertyQuery - { - private bool _allowGlobbingField; - - private bool _allowGlobbingFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool AllowGlobbing - { - get - { - return this._allowGlobbingField; - } - - set - { - this._allowGlobbingField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool AllowGlobbingSpecified - { - get - { - return this._allowGlobbingFieldSpecified; - } - - set - { - this._allowGlobbingFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] - public enum ItemsChoiceType - { - /// - ExcludeQuery, - - /// - MaxValueQuery, - - /// - MinValueQuery, - - /// - RegularQuery, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadataData - { - private string _nameField; - - private string _valueField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Name - { - get - { - return this._nameField; - } - - set - { - this._nameField = value; - } - } - - /// - [System.Xml.Serialization.XmlTextAttribute()] - public string Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class EnumMetadataEnum - { - private EnumMetadataEnumValue[] _valueField; - - private string _enumNameField; - - private string _underlyingTypeField; - - private bool _bitwiseFlagsField; - - private bool _bitwiseFlagsFieldSpecified; - - /// - [System.Xml.Serialization.XmlElementAttribute("Value")] - public EnumMetadataEnumValue[] Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string EnumName - { - get - { - return this._enumNameField; - } - - set - { - this._enumNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string UnderlyingType - { - get - { - return this._underlyingTypeField; - } - - set - { - this._underlyingTypeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool BitwiseFlags - { - get - { - return this._bitwiseFlagsField; - } - - set - { - this._bitwiseFlagsField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool BitwiseFlagsSpecified - { - get - { - return this._bitwiseFlagsFieldSpecified; - } - - set - { - this._bitwiseFlagsFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class EnumMetadataEnumValue - { - private string _nameField; - - private string _valueField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Name - { - get - { - return this._nameField; - } - - set - { - this._nameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - } -} diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs deleted file mode 100644 index dd1c6023cdb..00000000000 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ /dev/null @@ -1,10110 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! -// -// This file has been generated -// by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// -// Generation timestamp: 10/21/2013 18:29:23 - -#pragma warning disable -#if _DYNAMIC_XMLSERIALIZER_COMPILATION - -#endif - -namespace Microsoft.PowerShell.Cmdletization.Xml -{ - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializationWriter1 : System.Xml.Serialization.XmlSerializationWriter - { - public void Write50_PowerShellMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - return; - } - - TopLevelElement(); - Write39_PowerShellMetadata(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)o), false, false); - } - - public void Write51_ClassMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write36_ClassMetadata(@"ClassMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o), true, false); - } - - public void Write52_ClassMetadataInstanceCmdlets(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadataInstanceCmdlets", string.Empty); - return; - } - - TopLevelElement(); - Write40_ClassMetadataInstanceCmdlets(@"ClassMetadataInstanceCmdlets", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o), true, false); - } - - public void Write53_GetCmdletParameters(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"GetCmdletParameters", string.Empty); - return; - } - - TopLevelElement(); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o), true, false); - } - - public void Write54_PropertyMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"PropertyMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write15_PropertyMetadata(@"PropertyMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o), true, false); - } - - public void Write55_TypeMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"TypeMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write2_TypeMetadata(@"TypeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o), true, false); - } - - public void Write56_Association(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"Association", string.Empty); - return; - } - - TopLevelElement(); - Write17_Association(@"Association", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)o), true, false); - } - - public void Write57_AssociationAssociatedInstance(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"AssociationAssociatedInstance", string.Empty); - return; - } - - TopLevelElement(); - Write41_AssociationAssociatedInstance(@"AssociationAssociatedInstance", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o), true, false); - } - - public void Write58_CmdletParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write10_CmdletParameterMetadata(@"CmdletParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o), true, false); - } - - public void Write59_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletParameter", string.Empty); - return; - } - - TopLevelElement(); - Write11_Item(@"CmdletParameterMetadataForGetCmdletParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o), true, false); - } - - public void Write60_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletFilteringParameter", string.Empty); - return; - } - - TopLevelElement(); - Write12_Item(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o), true, false); - } - - public void Write61_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateCount", string.Empty); - return; - } - - TopLevelElement(); - Write42_Item(@"CmdletParameterMetadataValidateCount", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o), true, false); - } - - public void Write62_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateLength", string.Empty); - return; - } - - TopLevelElement(); - Write43_Item(@"CmdletParameterMetadataValidateLength", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o), true, false); - } - - public void Write63_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateRange", string.Empty); - return; - } - - TopLevelElement(); - Write44_Item(@"CmdletParameterMetadataValidateRange", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o), true, false); - } - - public void Write64_ObsoleteAttributeMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ObsoleteAttributeMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write7_ObsoleteAttributeMetadata(@"ObsoleteAttributeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o), true, false); - } - - public void Write65_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForInstanceMethodParameter", string.Empty); - return; - } - - TopLevelElement(); - Write9_Item(@"CmdletParameterMetadataForInstanceMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o), true, false); - } - - public void Write66_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForStaticMethodParameter", string.Empty); - return; - } - - TopLevelElement(); - Write8_Item(@"CmdletParameterMetadataForStaticMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o), true, false); - } - - public void Write67_QueryOption(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"QueryOption", string.Empty); - return; - } - - TopLevelElement(); - Write18_QueryOption(@"QueryOption", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o), true, false); - } - - public void Write68_GetCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"GetCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write22_GetCmdletMetadata(@"GetCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o), true, false); - } - - public void Write69_CommonCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write21_CommonCmdletMetadata(@"CommonCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o), true, false); - } - - public void Write70_ConfirmImpact(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"ConfirmImpact", string.Empty); - return; - } - - WriteElementString(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o))); - } - - public void Write71_StaticCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write34_StaticCmdletMetadata(@"StaticCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o), true, false); - } - - public void Write72_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticCmdletMetadataCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write45_Item(@"StaticCmdletMetadataCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o), true, false); - } - - public void Write73_CommonMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write29_CommonMethodMetadata(@"CommonMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o), true, false); - } - - public void Write74_StaticMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write28_StaticMethodMetadata(@"StaticMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o), true, false); - } - - public void Write75_CommonMethodParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write26_CommonMethodParameterMetadata(@"CommonMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o), true, false); - } - - public void Write76_StaticMethodParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write27_StaticMethodParameterMetadata(@"StaticMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o), true, false); - } - - public void Write77_CmdletOutputMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletOutputMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o), true, false); - } - - public void Write78_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write25_Item(@"InstanceMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o), true, false); - } - - public void Write79_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodMetadataReturnValue", string.Empty); - return; - } - - TopLevelElement(); - Write46_Item(@"CommonMethodMetadataReturnValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o), true, false); - } - - public void Write80_InstanceMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write30_InstanceMethodMetadata(@"InstanceMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o), true, false); - } - - public void Write81_InstanceCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write31_InstanceCmdletMetadata(@"InstanceCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o), true, false); - } - - public void Write82_PropertyQuery(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"PropertyQuery", string.Empty); - return; - } - - TopLevelElement(); - Write14_PropertyQuery(@"PropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o), true, false); - } - - public void Write83_WildcardablePropertyQuery(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"WildcardablePropertyQuery", string.Empty); - return; - } - - TopLevelElement(); - Write13_WildcardablePropertyQuery(@"WildcardablePropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o), true, false); - } - - public void Write84_ItemsChoiceType(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"ItemsChoiceType", string.Empty); - return; - } - - WriteElementString(@"ItemsChoiceType", @"", Write3_ItemsChoiceType(((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o))); - } - - public void Write85_ClassMetadataData(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadataData", string.Empty); - return; - } - - TopLevelElement(); - Write47_ClassMetadataData(@"ClassMetadataData", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o), true, false); - } - - public void Write86_EnumMetadataEnum(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"EnumMetadataEnum", string.Empty); - return; - } - - TopLevelElement(); - Write48_EnumMetadataEnum(@"EnumMetadataEnum", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o), true, false); - } - - public void Write87_EnumMetadataEnumValue(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"EnumMetadataEnumValue", string.Empty); - return; - } - - TopLevelElement(); - Write49_EnumMetadataEnumValue(@"EnumMetadataEnumValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o), true, false); - } - - private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"EnumMetadataEnumValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); - WriteEndElement(o); - } - - private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"EnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); - WriteAttribute(@"UnderlyingType", @"", ((global::System.String)o.@UnderlyingType)); - if (o.@BitwiseFlagsSpecified) - { - WriteAttribute(@"BitwiseFlags", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@BitwiseFlags))); - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write37_EnumMetadataEnumValue(@"Value", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)a[ia]), false, false); - } - } - } - - if (o.@BitwiseFlagsSpecified) - { - } - - WriteEndElement(o); - } - - private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); - WriteEndElement(o); - } - - private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) - { - WriteValue(((global::System.String)o.@Value)); - } - - WriteEndElement(o); - } - - private string Write3_ItemsChoiceType(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType v) - { - string s = null; - switch (v) - { - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery: s = @"ExcludeQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery: s = @"MaxValueQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery: s = @"MinValueQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery: s = @"RegularQuery"; break; - default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType"); - } - - return s; - } - - private void Write13_WildcardablePropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"WildcardablePropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - if (o.@AllowGlobbingSpecified) - { - WriteAttribute(@"AllowGlobbing", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@AllowGlobbing))); - } - - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - if (o.@AllowGlobbingSpecified) - { - } - - WriteEndElement(o); - } - - private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) - { - Writer.WriteString(" "); - } - - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - { - global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) - { - Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) - { - Writer.WriteString(" "); - } - - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ErrorOnNoMatchSpecified) - { - WriteAttribute(@"ErrorOnNoMatch", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ErrorOnNoMatch))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - if (o.@ErrorOnNoMatchSpecified) - { - } - - WriteEndElement(o); - } - - private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(@"ObsoleteAttributeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Message", @"", ((global::System.String)o.@Message)); - WriteEndElement(o); - } - - private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) - { - WriteNullTagLiteral(n, ns); - } - - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) - { - WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write1_Object(string n, string ns, global::System.Object o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::System.Object)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - Write49_EnumMetadataEnumValue(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - Write48_EnumMetadataEnum(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - Write47_ClassMetadataData(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - Write46_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - Write44_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - Write43_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - Write42_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - Write41_AssociationAssociatedInstance(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - Write40_ClassMetadataInstanceCmdlets(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) - { - Write36_ClassMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) - { - Write34_StaticCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) - { - Write31_InstanceCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) - { - Write26_CommonMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - Write27_StaticMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - Write25_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) - { - Write29_CommonMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - Write30_InstanceMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - Write28_StaticMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) - { - Write23_CmdletOutputMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) - { - Write22_GetCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) - { - Write21_CommonCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - Write45_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) - { - Write19_GetCmdletParameters(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) - { - Write18_QueryOption(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) - { - Write17_Association(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.Association)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) - { - Write15_PropertyMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) - { - Write14_PropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - Write13_WildcardablePropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) - { - Write10_CmdletParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - Write11_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - Write9_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - Write8_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) - { - Write7_ObsoleteAttributeMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) - { - Write2_TypeMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ItemsChoiceType", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Writer.WriteString(Write3_ItemsChoiceType((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o)); - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::System.String[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::System.String[] a = (global::System.String[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfPropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write15_PropertyMetadata(@"Property", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfAssociation", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write17_Association(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfQueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write18_QueryOption(@"Option", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ConfirmImpact", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Writer.WriteString(Write20_ConfirmImpact((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o)); - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfStaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write27_StaticMethodParameterMetadata(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfInstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write25_Item(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfStaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write34_StaticCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write35_ClassMetadataData(@"Data", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfEnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write38_EnumMetadataEnum(@"Enum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else - { - WriteTypedPrimitive(n, ns, o, true); - return; - } - } - - WriteStartElement(n, ns, o, false, null); - WriteEndElement(o); - } - - private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); - WriteAttribute(@"UnderlyingType", @"", ((global::System.String)o.@UnderlyingType)); - if (o.@BitwiseFlagsSpecified) - { - WriteAttribute(@"BitwiseFlags", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@BitwiseFlags))); - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write37_EnumMetadataEnumValue(@"Value", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)a[ia]), false, false); - } - } - } - - if (o.@BitwiseFlagsSpecified) - { - } - - WriteEndElement(o); - } - - private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) - { - WriteValue(((global::System.String)o.@Value)); - } - - WriteEndElement(o); - } - - private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write33_Item(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o.@CmdletMetadata), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])o.@Method; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write28_StaticMethodMetadata(@"Method", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - WriteAttribute(@"CmdletParameterSet", @"", ((global::System.String)o.@CmdletParameterSet)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o.@Parameters); - if (a != null) - { - WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write27_StaticMethodParameterMetadata(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write27_StaticMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write8_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o.@CmdletParameterMetadata), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write23_CmdletOutputMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - Write1_Object(@"ErrorCode", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ErrorCode), false, false); - WriteEndElement(o); - } - - private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForStaticMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write2_TypeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"TypeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PSType", @"", ((global::System.String)o.@PSType)); - WriteAttribute(@"ETSType", @"", ((global::System.String)o.@ETSType)); - WriteEndElement(o); - } - - private void Write24_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private string Write20_ConfirmImpact(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact v) - { - string s = null; - switch (v) - { - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@None: s = @"None"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Low: s = @"Low"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Medium: s = @"Medium"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@High: s = @"High"; break; - default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact"); - } - - return s; - } - - private void Write25_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write9_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o.@CmdletParameterMetadata), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForInstanceMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write18_QueryOption(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"QueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"OptionName", @"", ((global::System.String)o.@OptionName)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write11_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - { - global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) - { - Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write17_Association(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.Association o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Association", @"", ((global::System.String)o.@Association1)); - WriteAttribute(@"SourceRole", @"", ((global::System.String)o.@SourceRole)); - WriteAttribute(@"ResultRole", @"", ((global::System.String)o.@ResultRole)); - Write16_AssociationAssociatedInstance(@"AssociatedInstance", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o.@AssociatedInstance), false, false); - WriteEndElement(o); - } - - private void Write16_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"PropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PropertyName", @"", ((global::System.String)o.@PropertyName)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])o.@Items; - if (a != null) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[] c = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])o.@ItemsElementName; - if (c == null || c.Length < a.Length) - { - throw CreateInvalidChoiceIdentifierValueException(@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType", @"ItemsElementName"); - } - - for (int ia = 0; ia < a.Length; ia++) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery ai = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)a[ia]; - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType ci = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)c[ia]; - { - if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery"); - Write13_WildcardablePropertyQuery(@"RegularQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery"); - Write13_WildcardablePropertyQuery(@"ExcludeQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery"); - Write14_PropertyQuery(@"MaxValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery"); - Write14_PropertyQuery(@"MinValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); - } - else if ((object)(ai) != null) - { - throw CreateUnknownTypeException(ai); - } - } - } - } - } - - WriteEndElement(o); - } - - private void Write14_PropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - Write13_WildcardablePropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"PropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write10_CmdletParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - Write11_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - Write9_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - Write8_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - WriteEndElement(o); - } - - private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o.@QueryableProperties); - if (a != null) - { - WriteStartElement(@"QueryableProperties", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write15_PropertyMetadata(@"Property", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])((global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o.@QueryableAssociations); - if (a != null) - { - WriteStartElement(@"QueryableAssociations", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write17_Association(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o.@QueryOptions); - if (a != null) - { - WriteStartElement(@"QueryOptions", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write18_QueryOption(@"Option", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticCmdletMetadataCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - Write45_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private void Write22_GetCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"GetCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - WriteEndElement(o); - } - - private void Write30_InstanceMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o.@Parameters); - if (a != null) - { - WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write25_Item(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write29_CommonMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - Write30_InstanceMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - Write28_StaticMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - WriteEndElement(o); - } - - private void Write26_CommonMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - Write27_StaticMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - Write25_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - WriteEndElement(o); - } - - private void Write31_InstanceCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); - Write30_InstanceMethodMetadata(@"Method", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o.@Method), false, false); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - WriteEndElement(o); - } - - private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"CmdletAdapter", @"", ((global::System.String)o.@CmdletAdapter)); - WriteAttribute(@"ClassName", @"", ((global::System.String)o.@ClassName)); - WriteAttribute(@"ClassVersion", @"", ((global::System.String)o.@ClassVersion)); - WriteElementString(@"Version", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)o.@Version)); - WriteElementString(@"DefaultNoun", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)o.@DefaultNoun)); - Write32_ClassMetadataInstanceCmdlets(@"InstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o.@InstanceCmdlets), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o.@StaticCmdlets); - if (a != null) - { - WriteStartElement(@"StaticCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write34_StaticCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o.@CmdletAdapterPrivateData); - if (a != null) - { - WriteStartElement(@"CmdletAdapterPrivateData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write35_ClassMetadataData(@"Data", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write31_InstanceCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadataInstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write31_InstanceCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write41_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"AssociationAssociatedInstance", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write42_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write43_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write44_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write46_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodMetadataReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write36_ClassMetadata(@"Class", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o.@Class), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o.@Enums); - if (a != null) - { - WriteStartElement(@"Enums", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write38_EnumMetadataEnum(@"Enum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - protected override void InitCallbacks() - { - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializationReader1 : System.Xml.Serialization.XmlSerializationReader - { - public object Read50_PowerShellMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id1_PowerShellMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o = Read39_PowerShellMetadata(false, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); - } - - return (object)o; - } - - public object Read51_ClassMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id3_ClassMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read36_ClassMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadata"); - } - - return (object)o; - } - - public object Read52_ClassMetadataInstanceCmdlets() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id5_ClassMetadataInstanceCmdlets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read40_ClassMetadataInstanceCmdlets(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadataInstanceCmdlets"); - } - - return (object)o; - } - - public object Read53_GetCmdletParameters() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read19_GetCmdletParameters(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":GetCmdletParameters"); - } - - return (object)o; - } - - public object Read54_PropertyMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id7_PropertyMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read15_PropertyMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":PropertyMetadata"); - } - - return (object)o; - } - - public object Read55_TypeMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id8_TypeMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read2_TypeMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":TypeMetadata"); - } - - return (object)o; - } - - public object Read56_Association() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read17_Association(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":Association"); - } - - return (object)o; - } - - public object Read57_AssociationAssociatedInstance() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id10_AssociationAssociatedInstance && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read41_AssociationAssociatedInstance(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":AssociationAssociatedInstance"); - } - - return (object)o; - } - - public object Read58_CmdletParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read10_CmdletParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadata"); - } - - return (object)o; - } - - public object Read59_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id12_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read11_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); - } - - return (object)o; - } - - public object Read60_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id13_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read12_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); - } - - return (object)o; - } - - public object Read61_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id14_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read42_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateCount"); - } - - return (object)o; - } - - public object Read62_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id15_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read43_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateLength"); - } - - return (object)o; - } - - public object Read63_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id16_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read44_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateRange"); - } - - return (object)o; - } - - public object Read64_ObsoleteAttributeMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id17_ObsoleteAttributeMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read7_ObsoleteAttributeMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ObsoleteAttributeMetadata"); - } - - return (object)o; - } - - public object Read65_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id18_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read9_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); - } - - return (object)o; - } - - public object Read66_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id19_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read8_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); - } - - return (object)o; - } - - public object Read67_QueryOption() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id20_QueryOption && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read18_QueryOption(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":QueryOption"); - } - - return (object)o; - } - - public object Read68_GetCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id21_GetCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read22_GetCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":GetCmdletMetadata"); - } - - return (object)o; - } - - public object Read69_CommonCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id22_CommonCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read21_CommonCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonCmdletMetadata"); - } - - return (object)o; - } - - public object Read70_ConfirmImpact() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - { - o = Read20_ConfirmImpact(Reader.ReadElementString()); - } - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ConfirmImpact"); - } - - return (object)o; - } - - public object Read71_StaticCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id24_StaticCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read34_StaticCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticCmdletMetadata"); - } - - return (object)o; - } - - public object Read72_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id25_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read45_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); - } - - return (object)o; - } - - public object Read73_CommonMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id26_CommonMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read29_CommonMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodMetadata"); - } - - return (object)o; - } - - public object Read74_StaticMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id27_StaticMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read28_StaticMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticMethodMetadata"); - } - - return (object)o; - } - - public object Read75_CommonMethodParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id28_CommonMethodParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read26_CommonMethodParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read76_StaticMethodParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id29_StaticMethodParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read27_StaticMethodParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read77_CmdletOutputMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read23_CmdletOutputMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletOutputMetadata"); - } - - return (object)o; - } - - public object Read78_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id31_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read25_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read79_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id32_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read46_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodMetadataReturnValue"); - } - - return (object)o; - } - - public object Read80_InstanceMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id33_InstanceMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read30_InstanceMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceMethodMetadata"); - } - - return (object)o; - } - - public object Read81_InstanceCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id34_InstanceCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read31_InstanceCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceCmdletMetadata"); - } - - return (object)o; - } - - public object Read82_PropertyQuery() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id35_PropertyQuery && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read14_PropertyQuery(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":PropertyQuery"); - } - - return (object)o; - } - - public object Read83_WildcardablePropertyQuery() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id36_WildcardablePropertyQuery && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read13_WildcardablePropertyQuery(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":WildcardablePropertyQuery"); - } - - return (object)o; - } - - public object Read84_ItemsChoiceType() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id37_ItemsChoiceType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - { - o = Read3_ItemsChoiceType(Reader.ReadElementString()); - } - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ItemsChoiceType"); - } - - return (object)o; - } - - public object Read85_ClassMetadataData() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id38_ClassMetadataData && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read47_ClassMetadataData(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadataData"); - } - - return (object)o; - } - - public object Read86_EnumMetadataEnum() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id39_EnumMetadataEnum && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read48_EnumMetadataEnum(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":EnumMetadataEnum"); - } - - return (object)o; - } - - public object Read87_EnumMetadataEnumValue() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id40_EnumMetadataEnumValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read49_EnumMetadataEnumValue(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":EnumMetadataEnumValue"); - } - - return (object)o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read49_EnumMetadataEnumValue(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Value = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name, :Value"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations0 = 0; - int readerCount0 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations0, ref readerCount0); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read48_EnumMetadataEnum(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a_0 = null; - int ca_0 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id43_EnumName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@EnumName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@UnderlyingType = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id45_BitwiseFlags && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@BitwiseFlags = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@BitwiseFlagsSpecified = true; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations1 = 0; - int readerCount1 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])EnsureArrayIndex(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)); a_0[ca_0++] = Read37_EnumMetadataEnumValue(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations1, ref readerCount1); - } - - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read37_EnumMetadataEnumValue(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Value = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name, :Value"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations2 = 0; - int readerCount2 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations2, ref readerCount2); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read47_ClassMetadataData(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations3 = 0; - int readerCount3 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else if (Reader.NodeType == System.Xml.XmlNodeType.Text || - Reader.NodeType == System.Xml.XmlNodeType.CDATA || - Reader.NodeType == System.Xml.XmlNodeType.Whitespace || - Reader.NodeType == System.Xml.XmlNodeType.SignificantWhitespace) - { - tmp = ReadString(tmp, false); - o.@Value = tmp; - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations3, ref readerCount3); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType Read3_ItemsChoiceType(string s) - { - switch (s) - { - case @"ExcludeQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery; - case @"MaxValueQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery; - case @"MinValueQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery; - case @"RegularQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery; - default: throw CreateUnknownConstantException(s, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); - } - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery Read13_WildcardablePropertyQuery(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id46_AllowGlobbing && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@AllowGlobbing = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@AllowGlobbingSpecified = true; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":AllowGlobbing"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations4 = 0; - int readerCount4 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations4, ref readerCount4); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter Read12_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - global::System.String[] a_16 = null; - int ca_16 = 0; - bool[] paramsRead = new bool[18]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (((object)Reader.LocalName == (object)_id53_CmdletParameterSets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_16 = (global::System.String[])EnsureArrayIndex(a_16, ca_16, typeof(global::System.String)); a_16[ca_16++] = vals[i]; - } - } - else if (!paramsRead[17] && ((object)Reader.LocalName == (object)_id54_ErrorOnNoMatch && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ErrorOnNoMatch = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ErrorOnNoMatchSpecified = true; - paramsRead[17] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations5 = 0; - int readerCount5 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations6 = 0; - int readerCount6 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations6, ref readerCount6); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations5, ref readerCount5); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata Read7_ObsoleteAttributeMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata(); - bool[] paramsRead = new bool[1]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id66_Message && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Message = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Message"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations7 = 0; - int readerCount7 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations7, ref readerCount7); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read6_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations8 = 0; - int readerCount8 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations8, ref readerCount8); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read5_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations9 = 0; - int readerCount9 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations9, ref readerCount9); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read4_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations10 = 0; - int readerCount10 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations10, ref readerCount10); - } - - ReadEndElement(); - return o; - } - - private global::System.Object Read1_Object(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (isNull) - { - if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); - else return null; - } - - if (xsiType == null) - { - return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read49_EnumMetadataEnumValue(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read48_EnumMetadataEnum(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read47_ClassMetadataData(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read46_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read44_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read43_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read42_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read41_AssociationAssociatedInstance(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read40_ClassMetadataInstanceCmdlets(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read36_ClassMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read34_StaticCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read31_InstanceCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read26_CommonMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read27_StaticMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read25_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read29_CommonMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read30_InstanceMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read28_StaticMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read23_CmdletOutputMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read22_GetCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read21_CommonCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read45_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read19_GetCmdletParameters(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read18_QueryOption(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read17_Association(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read15_PropertyMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read14_PropertyQuery(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read13_WildcardablePropertyQuery(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read10_CmdletParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read11_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read9_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read8_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read7_ObsoleteAttributeMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read2_TypeMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id37_ItemsChoiceType && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - Reader.ReadStartElement(); - object e = Read3_ItemsChoiceType(CollapseWhitespace(Reader.ReadString())); - ReadEndElement(); - return e; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id69_ArrayOfString && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::System.String[] a = null; - if (!ReadNull()) - { - global::System.String[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations11 = 0; - int readerCount11 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - z_0_0 = (global::System.String[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::System.String)); z_0_0[cz_0_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations11, ref readerCount11); - } - - ReadEndElement(); - } - - a = (global::System.String[])ShrinkArray(z_0_0, cz_0_0, typeof(global::System.String), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id70_ArrayOfPropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations12 = 0; - int readerCount12 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id71_Property && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)); z_0_0[cz_0_0++] = Read15_PropertyMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations12, ref readerCount12); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id72_ArrayOfAssociation && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations13 = 0; - int readerCount13 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)); z_0_0[cz_0_0++] = Read17_Association(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations13, ref readerCount13); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id73_ArrayOfQueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations14 = 0; - int readerCount14 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id74_Option && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)); z_0_0[cz_0_0++] = Read18_QueryOption(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations14, ref readerCount14); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id23_ConfirmImpact && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - Reader.ReadStartElement(); - object e = Read20_ConfirmImpact(CollapseWhitespace(Reader.ReadString())); - ReadEndElement(); - return e; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id75_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations15 = 0; - int readerCount15 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)); z_0_0[cz_0_0++] = Read27_StaticMethodParameterMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations15, ref readerCount15); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id77_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations16 = 0; - int readerCount16 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)); z_0_0[cz_0_0++] = Read25_Item(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations16, ref readerCount16); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id78_ArrayOfStaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations17 = 0; - int readerCount17 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)); z_0_0[cz_0_0++] = Read34_StaticCmdletMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations17, ref readerCount17); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id80_ArrayOfClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations18 = 0; - int readerCount18 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id81_Data && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)); z_0_0[cz_0_0++] = Read35_ClassMetadataData(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations18, ref readerCount18); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id82_ArrayOfEnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations19 = 0; - int readerCount19 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id83_Enum && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)); z_0_0[cz_0_0++] = Read38_EnumMetadataEnum(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations19, ref readerCount19); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); - } - - return a; - } - else - return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::System.Object o; - o = new global::System.Object(); - bool[] paramsRead = Array.Empty(); - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations20 = 0; - int readerCount20 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations20, ref readerCount20); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read38_EnumMetadataEnum(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a_0 = null; - int ca_0 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id43_EnumName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@EnumName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@UnderlyingType = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id45_BitwiseFlags && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@BitwiseFlags = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@BitwiseFlagsSpecified = true; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations21 = 0; - int readerCount21 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])EnsureArrayIndex(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)); a_0[ca_0++] = Read37_EnumMetadataEnumValue(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations21, ref readerCount21); - } - - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read35_ClassMetadataData(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations22 = 0; - int readerCount22 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else if (Reader.NodeType == System.Xml.XmlNodeType.Text || - Reader.NodeType == System.Xml.XmlNodeType.CDATA || - Reader.NodeType == System.Xml.XmlNodeType.Whitespace || - Reader.NodeType == System.Xml.XmlNodeType.SignificantWhitespace) - { - tmp = ReadString(tmp, false); - o.@Value = tmp; - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations22, ref readerCount22); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata Read34_StaticCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[] a_1 = null; - int ca_1 = 0; - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations23 = 0; - int readerCount23 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read33_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id85_Method && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)); a_1[ca_1++] = Read28_StaticMethodMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations23, ref readerCount23); - } - - o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata Read28_StaticMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id87_CmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@CmdletParameterSet = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations24 = 0; - int readerCount24 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id89_Parameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations25 = 0; - int readerCount25 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)); a_2_0[ca_2_0++] = Read27_StaticMethodParameterMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations25, ref readerCount25); - } - - ReadEndElement(); - } - - o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations24, ref readerCount24); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata Read27_StaticMethodParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata(); - bool[] paramsRead = new bool[5]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations26 = 0; - int readerCount26 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read8_Item(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[4] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations26, ref readerCount26); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata Read23_CmdletOutputMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PSName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations27 = 0; - int readerCount27 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id93_ErrorCode && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ErrorCode = Read1_Object(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations27, ref readerCount27); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter Read8_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[16]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations28 = 0; - int readerCount28 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations29 = 0; - int readerCount29 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations29, ref readerCount29); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations28, ref readerCount28); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata Read2_TypeMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id94_PSType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSType = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id95_ETSType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ETSType = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PSType, :ETSType"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations30 = 0; - int readerCount30 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations30, ref readerCount30); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue Read24_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations31 = 0; - int readerCount31 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations31, ref readerCount31); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata Read33_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[7]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[6] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations32 = 0; - int readerCount32 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations32, ref readerCount32); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact Read20_ConfirmImpact(string s) - { - switch (s) - { - case @"None": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@None; - case @"Low": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Low; - case @"Medium": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Medium; - case @"High": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@High; - default: throw CreateUnknownConstantException(s, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)); - } - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata Read25_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata(); - bool[] paramsRead = new bool[5]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations33 = 0; - int readerCount33 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read9_Item(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[4] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations33, ref readerCount33); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter Read9_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[15]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[14] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipelineByPropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations34 = 0; - int readerCount34 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations35 = 0; - int readerCount35 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations35, ref readerCount35); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations34, ref readerCount34); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption Read18_QueryOption(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id100_OptionName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@OptionName = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":OptionName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations36 = 0; - int readerCount36 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read11_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations36, ref readerCount36); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter Read11_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - global::System.String[] a_16 = null; - int ca_16 = 0; - bool[] paramsRead = new bool[17]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (((object)Reader.LocalName == (object)_id53_CmdletParameterSets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_16 = (global::System.String[])EnsureArrayIndex(a_16, ca_16, typeof(global::System.String)); a_16[ca_16++] = vals[i]; - } - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations37 = 0; - int readerCount37 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations38 = 0; - int readerCount38 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations38, ref readerCount38); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations37, ref readerCount37); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.Association Read17_Association(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.Association o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.Association(); - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Association1 = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id101_SourceRole && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@SourceRole = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id102_ResultRole && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ResultRole = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Association, :SourceRole, :ResultRole"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations39 = 0; - int readerCount39 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id103_AssociatedInstance && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AssociatedInstance = Read16_AssociationAssociatedInstance(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations39, ref readerCount39); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance Read16_AssociationAssociatedInstance(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations40 = 0; - int readerCount40 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations40, ref readerCount40); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata Read15_PropertyMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[] a_1 = null; - int ca_1 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[] choice_a_1 = null; - int cchoice_a_1 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id104_PropertyName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PropertyName = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); - o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations41 = 0; - int readerCount41 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id105_MaxValueQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read14_PropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery; - } - else if (((object)Reader.LocalName == (object)_id106_RegularQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read13_WildcardablePropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery; - } - else if (((object)Reader.LocalName == (object)_id107_ExcludeQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read13_WildcardablePropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery; - } - else if (((object)Reader.LocalName == (object)_id108_MinValueQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read14_PropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations41, ref readerCount41); - } - - o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); - o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery Read14_PropertyQuery(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read13_WildcardablePropertyQuery(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery(); - bool[] paramsRead = new bool[1]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations42 = 0; - int readerCount42 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations42, ref readerCount42); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata Read10_CmdletParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read11_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read9_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read8_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[14]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations43 = 0; - int readerCount43 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations44 = 0; - int readerCount44 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations44, ref readerCount44); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations43, ref readerCount43); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters Read19_GetCmdletParameters(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters(); - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a_0 = null; - int ca_0 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a_1 = null; - int ca_1 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations45 = 0; - int readerCount45 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id109_QueryableProperties && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a_0_0 = null; - int ca_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations46 = 0; - int readerCount46 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id71_Property && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)); a_0_0[ca_0_0++] = Read15_PropertyMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations46, ref readerCount46); - } - - ReadEndElement(); - } - - o.@QueryableProperties = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); - } - } - else if (((object)Reader.LocalName == (object)_id110_QueryableAssociations && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a_1_0 = null; - int ca_1_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations47 = 0; - int readerCount47 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)); a_1_0[ca_1_0++] = Read17_Association(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations47, ref readerCount47); - } - - ReadEndElement(); - } - - o.@QueryableAssociations = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); - } - } - else if (((object)Reader.LocalName == (object)_id111_QueryOptions && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations48 = 0; - int readerCount48 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id74_Option && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)); a_2_0[ca_2_0++] = Read18_QueryOption(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations48, ref readerCount48); - } - - ReadEndElement(); - } - - o.@QueryOptions = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations45, ref readerCount45); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata Read45_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[7]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[6] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations49 = 0; - int readerCount49 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations49, ref readerCount49); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata Read21_CommonCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read45_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[6]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations50 = 0; - int readerCount50 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations50, ref readerCount50); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata Read22_GetCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations51 = 0; - int readerCount51 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read21_CommonCmdletMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations51, ref readerCount51); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata Read30_InstanceMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations52 = 0; - int readerCount52 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id89_Parameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations53 = 0; - int readerCount53 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)); a_2_0[ca_2_0++] = Read25_Item(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations53, ref readerCount53); - } - - ReadEndElement(); - } - - o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations52, ref readerCount52); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata Read29_CommonMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read30_InstanceMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read28_StaticMethodMetadata(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations54 = 0; - int readerCount54 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations54, ref readerCount54); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata Read26_CommonMethodParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read27_StaticMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read25_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations55 = 0; - int readerCount55 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations55, ref readerCount55); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata Read31_InstanceCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations56 = 0; - int readerCount56 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read21_CommonCmdletMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id85_Method && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Method = Read30_InstanceMethodMetadata(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[2] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations56, ref readerCount56); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata Read36_ClassMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a_3 = null; - int ca_3 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a_4 = null; - int ca_4 = 0; - bool[] paramsRead = new bool[8]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id112_CmdletAdapter && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@CmdletAdapter = Reader.Value; - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id113_ClassName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ClassName = Reader.Value; - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id114_ClassVersion && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ClassVersion = Reader.Value; - paramsRead[7] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":CmdletAdapter, :ClassName, :ClassVersion"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations57 = 0; - int readerCount57 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id115_Version && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - o.@Version = Reader.ReadElementString(); - } - - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id116_DefaultNoun && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - o.@DefaultNoun = Reader.ReadElementString(); - } - - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id117_InstanceCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@InstanceCmdlets = Read32_ClassMetadataInstanceCmdlets(false, true); - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id118_StaticCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a_3_0 = null; - int ca_3_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations58 = 0; - int readerCount58 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_3_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])EnsureArrayIndex(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)); a_3_0[ca_3_0++] = Read34_StaticCmdletMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations58, ref readerCount58); - } - - ReadEndElement(); - } - - o.@StaticCmdlets = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); - } - } - else if (((object)Reader.LocalName == (object)_id119_CmdletAdapterPrivateData && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a_4_0 = null; - int ca_4_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations59 = 0; - int readerCount59 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id81_Data && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_4_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])EnsureArrayIndex(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)); a_4_0[ca_4_0++] = Read35_ClassMetadataData(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations59, ref readerCount59); - } - - ReadEndElement(); - } - - o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations57, ref readerCount57); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets Read32_ClassMetadataInstanceCmdlets(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations60 = 0; - int readerCount60 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id120_GetCmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdlet = Read22_GetCmdletMetadata(false, true); - paramsRead[1] = true; - } - else if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])EnsureArrayIndex(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)); a_2[ca_2++] = Read31_InstanceCmdletMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations60, ref readerCount60); - } - - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets Read40_ClassMetadataInstanceCmdlets(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations61 = 0; - int readerCount61 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id120_GetCmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdlet = Read22_GetCmdletMetadata(false, true); - paramsRead[1] = true; - } - else if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])EnsureArrayIndex(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)); a_2[ca_2++] = Read31_InstanceCmdletMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations61, ref readerCount61); - } - - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance Read41_AssociationAssociatedInstance(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations62 = 0; - int readerCount62 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations62, ref readerCount62); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read42_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations63 = 0; - int readerCount63 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations63, ref readerCount63); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read43_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations64 = 0; - int readerCount64 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations64, ref readerCount64); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read44_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations65 = 0; - int readerCount65 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations65, ref readerCount65); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue Read46_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations66 = 0; - int readerCount66 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations66, ref readerCount66); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata Read39_PowerShellMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a_1 = null; - int ca_1 = 0; - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations67 = 0; - int readerCount67 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id121_Class && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Class = Read36_ClassMetadata(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id122_Enums && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a_1_0 = null; - int ca_1_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations68 = 0; - int readerCount68 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id83_Enum && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)); a_1_0[ca_1_0++] = Read38_EnumMetadataEnum(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations68, ref readerCount68); - } - - ReadEndElement(); - } - - o.@Enums = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations67, ref readerCount67); - } - - ReadEndElement(); - return o; - } - - protected override void InitCallbacks() - { - } - - private string _id72_ArrayOfAssociation; - private string _id46_AllowGlobbing; - private string _id6_GetCmdletParameters; - private string _id25_Item; - private string _id62_ValidateRange; - private string _id118_StaticCmdlets; - private string _id58_ValidateNotNull; - private string _id17_ObsoleteAttributeMetadata; - private string _id49_PSName; - private string _id116_DefaultNoun; - private string _id38_ClassMetadataData; - private string _id114_ClassVersion; - private string _id66_Message; - private string _id65_Obsolete; - private string _id51_ValueFromPipeline; - private string _id108_MinValueQuery; - private string _id119_CmdletAdapterPrivateData; - private string _id21_GetCmdletMetadata; - private string _id120_GetCmdlet; - private string _id67_Min; - private string _id56_AllowEmptyString; - private string _id30_CmdletOutputMetadata; - private string _id106_RegularQuery; - private string _id74_Option; - private string _id75_Item; - private string _id23_ConfirmImpact; - private string _id117_InstanceCmdlets; - private string _id83_Enum; - private string _id40_EnumMetadataEnumValue; - private string _id111_QueryOptions; - private string _id34_InstanceCmdletMetadata; - private string _id60_ValidateCount; - private string _id45_BitwiseFlags; - private string _id81_Data; - private string _id31_Item; - private string _id1_PowerShellMetadata; - private string _id98_HelpUri; - private string _id91_DefaultValue; - private string _id4_Item; - private string _id32_Item; - private string _id43_EnumName; - private string _id122_Enums; - private string _id82_ArrayOfEnumMetadataEnum; - private string _id14_Item; - private string _id48_Aliases; - private string _id115_Version; - private string _id11_CmdletParameterMetadata; - private string _id70_ArrayOfPropertyMetadata; - private string _id9_Association; - private string _id102_ResultRole; - private string _id29_StaticMethodParameterMetadata; - private string _id97_Noun; - private string _id47_IsMandatory; - private string _id35_PropertyQuery; - private string _id54_ErrorOnNoMatch; - private string _id3_ClassMetadata; - private string _id77_Item; - private string _id2_Item; - private string _id22_CommonCmdletMetadata; - private string _id37_ItemsChoiceType; - private string _id36_WildcardablePropertyQuery; - private string _id113_ClassName; - private string _id64_AllowedValue; - private string _id52_Item; - private string _id55_AllowEmptyCollection; - private string _id13_Item; - private string _id76_Parameter; - private string _id19_Item; - private string _id105_MaxValueQuery; - private string _id101_SourceRole; - private string _id5_ClassMetadataInstanceCmdlets; - private string _id112_CmdletAdapter; - private string _id10_AssociationAssociatedInstance; - private string _id93_ErrorCode; - private string _id41_Name; - private string _id68_Max; - private string _id50_Position; - private string _id100_OptionName; - private string _id84_CmdletMetadata; - private string _id87_CmdletParameterSet; - private string _id104_PropertyName; - private string _id28_CommonMethodParameterMetadata; - private string _id107_ExcludeQuery; - private string _id92_Type; - private string _id33_InstanceMethodMetadata; - private string _id63_ValidateSet; - private string _id53_CmdletParameterSets; - private string _id15_Item; - private string _id109_QueryableProperties; - private string _id57_AllowNull; - private string _id80_ArrayOfClassMetadataData; - private string _id99_DefaultCmdletParameterSet; - private string _id20_QueryOption; - private string _id89_Parameters; - private string _id90_ParameterName; - private string _id61_ValidateLength; - private string _id78_ArrayOfStaticCmdletMetadata; - private string _id16_Item; - private string _id39_EnumMetadataEnum; - private string _id7_PropertyMetadata; - private string _id110_QueryableAssociations; - private string _id86_MethodName; - private string _id8_TypeMetadata; - private string _id71_Property; - private string _id27_StaticMethodMetadata; - private string _id94_PSType; - private string _id44_UnderlyingType; - private string _id103_AssociatedInstance; - private string _id79_Cmdlet; - private string _id18_Item; - private string _id85_Method; - private string _id95_ETSType; - private string _id26_CommonMethodMetadata; - private string _id88_ReturnValue; - private string _id69_ArrayOfString; - private string _id24_StaticCmdletMetadata; - private string _id59_ValidateNotNullOrEmpty; - private string _id96_Verb; - private string _id121_Class; - private string _id73_ArrayOfQueryOption; - private string _id12_Item; - private string _id42_Value; - - protected override void InitIDs() - { - _id72_ArrayOfAssociation = Reader.NameTable.Add(@"ArrayOfAssociation"); - _id46_AllowGlobbing = Reader.NameTable.Add(@"AllowGlobbing"); - _id6_GetCmdletParameters = Reader.NameTable.Add(@"GetCmdletParameters"); - _id25_Item = Reader.NameTable.Add(@"StaticCmdletMetadataCmdletMetadata"); - _id62_ValidateRange = Reader.NameTable.Add(@"ValidateRange"); - _id118_StaticCmdlets = Reader.NameTable.Add(@"StaticCmdlets"); - _id58_ValidateNotNull = Reader.NameTable.Add(@"ValidateNotNull"); - _id17_ObsoleteAttributeMetadata = Reader.NameTable.Add(@"ObsoleteAttributeMetadata"); - _id49_PSName = Reader.NameTable.Add(@"PSName"); - _id116_DefaultNoun = Reader.NameTable.Add(@"DefaultNoun"); - _id38_ClassMetadataData = Reader.NameTable.Add(@"ClassMetadataData"); - _id114_ClassVersion = Reader.NameTable.Add(@"ClassVersion"); - _id66_Message = Reader.NameTable.Add(@"Message"); - _id65_Obsolete = Reader.NameTable.Add(@"Obsolete"); - _id51_ValueFromPipeline = Reader.NameTable.Add(@"ValueFromPipeline"); - _id108_MinValueQuery = Reader.NameTable.Add(@"MinValueQuery"); - _id119_CmdletAdapterPrivateData = Reader.NameTable.Add(@"CmdletAdapterPrivateData"); - _id21_GetCmdletMetadata = Reader.NameTable.Add(@"GetCmdletMetadata"); - _id120_GetCmdlet = Reader.NameTable.Add(@"GetCmdlet"); - _id67_Min = Reader.NameTable.Add(@"Min"); - _id56_AllowEmptyString = Reader.NameTable.Add(@"AllowEmptyString"); - _id30_CmdletOutputMetadata = Reader.NameTable.Add(@"CmdletOutputMetadata"); - _id106_RegularQuery = Reader.NameTable.Add(@"RegularQuery"); - _id74_Option = Reader.NameTable.Add(@"Option"); - _id75_Item = Reader.NameTable.Add(@"ArrayOfStaticMethodParameterMetadata"); - _id23_ConfirmImpact = Reader.NameTable.Add(@"ConfirmImpact"); - _id117_InstanceCmdlets = Reader.NameTable.Add(@"InstanceCmdlets"); - _id83_Enum = Reader.NameTable.Add(@"Enum"); - _id40_EnumMetadataEnumValue = Reader.NameTable.Add(@"EnumMetadataEnumValue"); - _id111_QueryOptions = Reader.NameTable.Add(@"QueryOptions"); - _id34_InstanceCmdletMetadata = Reader.NameTable.Add(@"InstanceCmdletMetadata"); - _id60_ValidateCount = Reader.NameTable.Add(@"ValidateCount"); - _id45_BitwiseFlags = Reader.NameTable.Add(@"BitwiseFlags"); - _id81_Data = Reader.NameTable.Add(@"Data"); - _id31_Item = Reader.NameTable.Add(@"InstanceMethodParameterMetadata"); - _id1_PowerShellMetadata = Reader.NameTable.Add(@"PowerShellMetadata"); - _id98_HelpUri = Reader.NameTable.Add(@"HelpUri"); - _id91_DefaultValue = Reader.NameTable.Add(@"DefaultValue"); - _id4_Item = Reader.NameTable.Add(string.Empty); - _id32_Item = Reader.NameTable.Add(@"CommonMethodMetadataReturnValue"); - _id43_EnumName = Reader.NameTable.Add(@"EnumName"); - _id122_Enums = Reader.NameTable.Add(@"Enums"); - _id82_ArrayOfEnumMetadataEnum = Reader.NameTable.Add(@"ArrayOfEnumMetadataEnum"); - _id14_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateCount"); - _id48_Aliases = Reader.NameTable.Add(@"Aliases"); - _id115_Version = Reader.NameTable.Add(@"Version"); - _id11_CmdletParameterMetadata = Reader.NameTable.Add(@"CmdletParameterMetadata"); - _id70_ArrayOfPropertyMetadata = Reader.NameTable.Add(@"ArrayOfPropertyMetadata"); - _id9_Association = Reader.NameTable.Add(@"Association"); - _id102_ResultRole = Reader.NameTable.Add(@"ResultRole"); - _id29_StaticMethodParameterMetadata = Reader.NameTable.Add(@"StaticMethodParameterMetadata"); - _id97_Noun = Reader.NameTable.Add(@"Noun"); - _id47_IsMandatory = Reader.NameTable.Add(@"IsMandatory"); - _id35_PropertyQuery = Reader.NameTable.Add(@"PropertyQuery"); - _id54_ErrorOnNoMatch = Reader.NameTable.Add(@"ErrorOnNoMatch"); - _id3_ClassMetadata = Reader.NameTable.Add(@"ClassMetadata"); - _id77_Item = Reader.NameTable.Add(@"ArrayOfInstanceMethodParameterMetadata"); - _id2_Item = Reader.NameTable.Add(@"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - _id22_CommonCmdletMetadata = Reader.NameTable.Add(@"CommonCmdletMetadata"); - _id37_ItemsChoiceType = Reader.NameTable.Add(@"ItemsChoiceType"); - _id36_WildcardablePropertyQuery = Reader.NameTable.Add(@"WildcardablePropertyQuery"); - _id113_ClassName = Reader.NameTable.Add(@"ClassName"); - _id64_AllowedValue = Reader.NameTable.Add(@"AllowedValue"); - _id52_Item = Reader.NameTable.Add(@"ValueFromPipelineByPropertyName"); - _id55_AllowEmptyCollection = Reader.NameTable.Add(@"AllowEmptyCollection"); - _id13_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForGetCmdletFilteringParameter"); - _id76_Parameter = Reader.NameTable.Add(@"Parameter"); - _id19_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForStaticMethodParameter"); - _id105_MaxValueQuery = Reader.NameTable.Add(@"MaxValueQuery"); - _id101_SourceRole = Reader.NameTable.Add(@"SourceRole"); - _id5_ClassMetadataInstanceCmdlets = Reader.NameTable.Add(@"ClassMetadataInstanceCmdlets"); - _id112_CmdletAdapter = Reader.NameTable.Add(@"CmdletAdapter"); - _id10_AssociationAssociatedInstance = Reader.NameTable.Add(@"AssociationAssociatedInstance"); - _id93_ErrorCode = Reader.NameTable.Add(@"ErrorCode"); - _id41_Name = Reader.NameTable.Add(@"Name"); - _id68_Max = Reader.NameTable.Add(@"Max"); - _id50_Position = Reader.NameTable.Add(@"Position"); - _id100_OptionName = Reader.NameTable.Add(@"OptionName"); - _id84_CmdletMetadata = Reader.NameTable.Add(@"CmdletMetadata"); - _id87_CmdletParameterSet = Reader.NameTable.Add(@"CmdletParameterSet"); - _id104_PropertyName = Reader.NameTable.Add(@"PropertyName"); - _id28_CommonMethodParameterMetadata = Reader.NameTable.Add(@"CommonMethodParameterMetadata"); - _id107_ExcludeQuery = Reader.NameTable.Add(@"ExcludeQuery"); - _id92_Type = Reader.NameTable.Add(@"Type"); - _id33_InstanceMethodMetadata = Reader.NameTable.Add(@"InstanceMethodMetadata"); - _id63_ValidateSet = Reader.NameTable.Add(@"ValidateSet"); - _id53_CmdletParameterSets = Reader.NameTable.Add(@"CmdletParameterSets"); - _id15_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateLength"); - _id109_QueryableProperties = Reader.NameTable.Add(@"QueryableProperties"); - _id57_AllowNull = Reader.NameTable.Add(@"AllowNull"); - _id80_ArrayOfClassMetadataData = Reader.NameTable.Add(@"ArrayOfClassMetadataData"); - _id99_DefaultCmdletParameterSet = Reader.NameTable.Add(@"DefaultCmdletParameterSet"); - _id20_QueryOption = Reader.NameTable.Add(@"QueryOption"); - _id89_Parameters = Reader.NameTable.Add(@"Parameters"); - _id90_ParameterName = Reader.NameTable.Add(@"ParameterName"); - _id61_ValidateLength = Reader.NameTable.Add(@"ValidateLength"); - _id78_ArrayOfStaticCmdletMetadata = Reader.NameTable.Add(@"ArrayOfStaticCmdletMetadata"); - _id16_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateRange"); - _id39_EnumMetadataEnum = Reader.NameTable.Add(@"EnumMetadataEnum"); - _id7_PropertyMetadata = Reader.NameTable.Add(@"PropertyMetadata"); - _id110_QueryableAssociations = Reader.NameTable.Add(@"QueryableAssociations"); - _id86_MethodName = Reader.NameTable.Add(@"MethodName"); - _id8_TypeMetadata = Reader.NameTable.Add(@"TypeMetadata"); - _id71_Property = Reader.NameTable.Add(@"Property"); - _id27_StaticMethodMetadata = Reader.NameTable.Add(@"StaticMethodMetadata"); - _id94_PSType = Reader.NameTable.Add(@"PSType"); - _id44_UnderlyingType = Reader.NameTable.Add(@"UnderlyingType"); - _id103_AssociatedInstance = Reader.NameTable.Add(@"AssociatedInstance"); - _id79_Cmdlet = Reader.NameTable.Add(@"Cmdlet"); - _id18_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForInstanceMethodParameter"); - _id85_Method = Reader.NameTable.Add(@"Method"); - _id95_ETSType = Reader.NameTable.Add(@"ETSType"); - _id26_CommonMethodMetadata = Reader.NameTable.Add(@"CommonMethodMetadata"); - _id88_ReturnValue = Reader.NameTable.Add(@"ReturnValue"); - _id69_ArrayOfString = Reader.NameTable.Add(@"ArrayOfString"); - _id24_StaticCmdletMetadata = Reader.NameTable.Add(@"StaticCmdletMetadata"); - _id59_ValidateNotNullOrEmpty = Reader.NameTable.Add(@"ValidateNotNullOrEmpty"); - _id96_Verb = Reader.NameTable.Add(@"Verb"); - _id121_Class = Reader.NameTable.Add(@"Class"); - _id73_ArrayOfQueryOption = Reader.NameTable.Add(@"ArrayOfQueryOption"); - _id12_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForGetCmdletParameter"); - _id42_Value = Reader.NameTable.Add(@"Value"); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal abstract class XmlSerializer1 : System.Xml.Serialization.XmlSerializer - { - protected override System.Xml.Serialization.XmlSerializationReader CreateReader() - { - return new XmlSerializationReader1(); - } - - protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter() - { - return new XmlSerializationWriter1(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PowerShellMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write50_PowerShellMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read50_PowerShellMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write51_ClassMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read51_ClassMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataInstanceCmdletsSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadataInstanceCmdlets", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write52_ClassMetadataInstanceCmdlets(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read52_ClassMetadataInstanceCmdlets(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class GetCmdletParametersSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"GetCmdletParameters", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write53_GetCmdletParameters(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read53_GetCmdletParameters(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PropertyMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PropertyMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write54_PropertyMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read54_PropertyMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class TypeMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"TypeMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write55_TypeMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read55_TypeMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class AssociationSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"Association", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write56_Association(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read56_Association(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class AssociationAssociatedInstanceSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"AssociationAssociatedInstance", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write57_AssociationAssociatedInstance(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read57_AssociationAssociatedInstance(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write58_CmdletParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read58_CmdletParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForGetCmdletParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write59_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read59_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForGetCmdletFilteringParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletFilteringParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write60_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read60_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateCountSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateCount", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write61_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read61_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateLengthSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateLength", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write62_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read62_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateRangeSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateRange", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write63_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read63_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ObsoleteAttributeMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ObsoleteAttributeMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write64_ObsoleteAttributeMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read64_ObsoleteAttributeMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForInstanceMethodParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForInstanceMethodParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write65_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read65_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForStaticMethodParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForStaticMethodParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write66_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read66_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class QueryOptionSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"QueryOption", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write67_QueryOption(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read67_QueryOption(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class GetCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"GetCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write68_GetCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read68_GetCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write69_CommonCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read69_CommonCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ConfirmImpactSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ConfirmImpact", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write70_ConfirmImpact(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read70_ConfirmImpact(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write71_StaticCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read71_StaticCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticCmdletMetadataCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticCmdletMetadataCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write72_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read72_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write73_CommonMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read73_CommonMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write74_StaticMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read74_StaticMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write75_CommonMethodParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read75_CommonMethodParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write76_StaticMethodParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read76_StaticMethodParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletOutputMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletOutputMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write77_CmdletOutputMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read77_CmdletOutputMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write78_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read78_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodMetadataReturnValueSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodMetadataReturnValue", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write79_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read79_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write80_InstanceMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read80_InstanceMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write81_InstanceCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read81_InstanceCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PropertyQuerySerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PropertyQuery", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write82_PropertyQuery(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read82_PropertyQuery(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class WildcardablePropertyQuerySerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"WildcardablePropertyQuery", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write83_WildcardablePropertyQuery(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read83_WildcardablePropertyQuery(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ItemsChoiceTypeSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ItemsChoiceType", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write84_ItemsChoiceType(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read84_ItemsChoiceType(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataDataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadataData", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write85_ClassMetadataData(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read85_ClassMetadataData(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class EnumMetadataEnumSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"EnumMetadataEnum", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write86_EnumMetadataEnum(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read86_EnumMetadataEnum(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class EnumMetadataEnumValueSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"EnumMetadataEnumValue", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write87_EnumMetadataEnumValue(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read87_EnumMetadataEnumValue(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation - { - public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReader1(); } } - - public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriter1(); } } - - private System.Collections.Hashtable _readMethods = null; - public override System.Collections.Hashtable ReadMethods - { - get - { - if (_readMethods == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:"] = @"Read50_PowerShellMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::"] = @"Read51_ClassMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::"] = @"Read52_ClassMetadataInstanceCmdlets"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::"] = @"Read53_GetCmdletParameters"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::"] = @"Read54_PropertyMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::"] = @"Read55_TypeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.Association::"] = @"Read56_Association"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::"] = @"Read57_AssociationAssociatedInstance"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::"] = @"Read58_CmdletParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::"] = @"Read59_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::"] = @"Read60_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::"] = @"Read61_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::"] = @"Read62_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::"] = @"Read63_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::"] = @"Read64_ObsoleteAttributeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::"] = @"Read65_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::"] = @"Read66_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::"] = @"Read67_QueryOption"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::"] = @"Read68_GetCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::"] = @"Read69_CommonCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::"] = @"Read70_ConfirmImpact"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::"] = @"Read71_StaticCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::"] = @"Read72_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::"] = @"Read73_CommonMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::"] = @"Read74_StaticMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::"] = @"Read75_CommonMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::"] = @"Read76_StaticMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::"] = @"Read77_CmdletOutputMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::"] = @"Read78_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::"] = @"Read79_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::"] = @"Read80_InstanceMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::"] = @"Read81_InstanceCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::"] = @"Read82_PropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::"] = @"Read83_WildcardablePropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::"] = @"Read84_ItemsChoiceType"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::"] = @"Read85_ClassMetadataData"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::"] = @"Read86_EnumMetadataEnum"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Read87_EnumMetadataEnumValue"; - if (_readMethods == null) _readMethods = _tmp; - } - - return _readMethods; - } - } - - private System.Collections.Hashtable _writeMethods = null; - public override System.Collections.Hashtable WriteMethods - { - get - { - if (_writeMethods == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:"] = @"Write50_PowerShellMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::"] = @"Write51_ClassMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::"] = @"Write52_ClassMetadataInstanceCmdlets"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::"] = @"Write53_GetCmdletParameters"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::"] = @"Write54_PropertyMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::"] = @"Write55_TypeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.Association::"] = @"Write56_Association"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::"] = @"Write57_AssociationAssociatedInstance"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::"] = @"Write58_CmdletParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::"] = @"Write59_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::"] = @"Write60_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::"] = @"Write61_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::"] = @"Write62_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::"] = @"Write63_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::"] = @"Write64_ObsoleteAttributeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::"] = @"Write65_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::"] = @"Write66_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::"] = @"Write67_QueryOption"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::"] = @"Write68_GetCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::"] = @"Write69_CommonCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::"] = @"Write70_ConfirmImpact"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::"] = @"Write71_StaticCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::"] = @"Write72_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::"] = @"Write73_CommonMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::"] = @"Write74_StaticMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::"] = @"Write75_CommonMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::"] = @"Write76_StaticMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::"] = @"Write77_CmdletOutputMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::"] = @"Write78_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::"] = @"Write79_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::"] = @"Write80_InstanceMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::"] = @"Write81_InstanceCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::"] = @"Write82_PropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::"] = @"Write83_WildcardablePropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::"] = @"Write84_ItemsChoiceType"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::"] = @"Write85_ClassMetadataData"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::"] = @"Write86_EnumMetadataEnum"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Write87_EnumMetadataEnumValue"; - if (_writeMethods == null) _writeMethods = _tmp; - } - - return _writeMethods; - } - } - - private System.Collections.Hashtable _typedSerializers = null; - public override System.Collections.Hashtable TypedSerializers - { - get - { - if (_typedSerializers == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::", new AssociationAssociatedInstanceSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.Association::", new AssociationSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::", new ClassMetadataInstanceCmdletsSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:", new PowerShellMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::", new EnumMetadataEnumValueSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::", new StaticCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::", new ItemsChoiceTypeSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::", new PropertyQuerySerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::", new CmdletParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::", new CommonMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::", new StaticMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::", new ObsoleteAttributeMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::", new InstanceCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::", new CommonMethodMetadataReturnValueSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::", new PropertyMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::", new CmdletParameterMetadataForGetCmdletParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::", new CmdletOutputMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::", new EnumMetadataEnumSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::", new QueryOptionSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::", new InstanceMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::", new CmdletParameterMetadataValidateRangeSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::", new ClassMetadataDataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::", new ConfirmImpactSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::", new StaticCmdletMetadataCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::", new GetCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::", new CmdletParameterMetadataValidateLengthSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::", new InstanceMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::", new CommonMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::", new CmdletParameterMetadataValidateCountSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::", new GetCmdletParametersSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::", new CmdletParameterMetadataForInstanceMethodParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::", new CommonCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::", new TypeMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::", new CmdletParameterMetadataForGetCmdletFilteringParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::", new StaticMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::", new CmdletParameterMetadataForStaticMethodParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::", new ClassMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::", new WildcardablePropertyQuerySerializer()); - if (_typedSerializers == null) _typedSerializers = _tmp; - } - - return _typedSerializers; - } - } - - public override bool CanSerialize(System.Type type) - { - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) return true; - return false; - } - - public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) - { - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return new PowerShellMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) return new ClassMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) return new ClassMetadataInstanceCmdletsSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) return new GetCmdletParametersSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) return new PropertyMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) return new TypeMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) return new AssociationSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) return new AssociationAssociatedInstanceSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) return new CmdletParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) return new CmdletParameterMetadataForGetCmdletParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) return new CmdletParameterMetadataForGetCmdletFilteringParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) return new CmdletParameterMetadataValidateCountSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) return new CmdletParameterMetadataValidateLengthSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) return new CmdletParameterMetadataValidateRangeSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) return new ObsoleteAttributeMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) return new CmdletParameterMetadataForInstanceMethodParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) return new CmdletParameterMetadataForStaticMethodParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) return new QueryOptionSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) return new GetCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) return new CommonCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) return new ConfirmImpactSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) return new StaticCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) return new StaticCmdletMetadataCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) return new CommonMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) return new StaticMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) return new CommonMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) return new StaticMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) return new CmdletOutputMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) return new InstanceMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) return new CommonMethodMetadataReturnValueSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) return new InstanceMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) return new InstanceCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) return new PropertyQuerySerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) return new WildcardablePropertyQuerySerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) return new ItemsChoiceTypeSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) return new ClassMetadataDataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) return new EnumMetadataEnumSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) return new EnumMetadataEnumValueSerializer(); - return null; - } - } -} diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs deleted file mode 100644 index 05eab93d198..00000000000 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Text; -using System.Transactions; - -namespace Microsoft.PowerShell.Commands.Management -{ - /// - /// Represents a string that can be used in transactions. - /// - public class TransactedString : IEnlistmentNotification - { - private StringBuilder _value; - private StringBuilder _temporaryValue; - private Transaction _enlistedTransaction = null; - - /// - /// Constructor for the TransactedString class. - /// - public TransactedString() : this(string.Empty) - { - } - - /// - /// Constructor for the TransactedString class. - /// - /// - /// The initial value of the transacted string. - /// - public TransactedString(string value) - { - _value = new StringBuilder(value); - _temporaryValue = null; - } - - /// - /// Make the transacted changes permanent. - /// - void IEnlistmentNotification.Commit(Enlistment enlistment) - { - _value = new StringBuilder(_temporaryValue.ToString()); - _temporaryValue = null; - _enlistedTransaction = null; - enlistment.Done(); - } - - /// - /// Discard the transacted changes. - /// - void IEnlistmentNotification.Rollback(Enlistment enlistment) - { - _temporaryValue = null; - _enlistedTransaction = null; - enlistment.Done(); - } - - /// - /// Discard the transacted changes. - /// - void IEnlistmentNotification.InDoubt(Enlistment enlistment) - { - enlistment.Done(); - } - - void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) - { - preparingEnlistment.Prepared(); - } - - /// - /// Append text to the transacted string. - /// - /// - /// The text to append. - /// - public void Append(string text) - { - ValidateTransactionOrEnlist(); - - if (_enlistedTransaction != null) - { - _temporaryValue.Append(text); - } - else - { - _value.Append(text); - } - } - - /// - /// Remove text from the transacted string. - /// - /// - /// The position in the string from which to start removing. - /// - /// - /// The length of text to remove. - /// - public void Remove(int startIndex, int length) - { - ValidateTransactionOrEnlist(); - - if (_enlistedTransaction != null) - { - _temporaryValue.Remove(startIndex, length); - } - else - { - _value.Remove(startIndex, length); - } - } - - /// - /// Gets the length of the transacted string. If this is - /// called within the transaction, it returns the length of - /// the transacted value. Otherwise, it returns the length of - /// the original value. - /// - public int Length - { - get - { - // If we're not in a transaction, or we are in a different transaction than the one we - // enlisted to, return the publicly visible state. - if ( - (Transaction.Current == null) || - (_enlistedTransaction != Transaction.Current)) - { - return _value.Length; - } - else - { - return _temporaryValue.Length; - } - } - } - - /// - /// Gets the System.String that represents the transacted - /// transacted string. If this is called within the - /// transaction, it returns the transacted value. - /// Otherwise, it returns the original value. - /// - public override string ToString() - { - // If we're not in a transaction, or we are in a different transaction than the one we - // enlisted to, return the publicly visible state. - if ( - (Transaction.Current == null) || - (_enlistedTransaction != Transaction.Current)) - { - return _value.ToString(); - } - else - { - return _temporaryValue.ToString(); - } - } - - private void ValidateTransactionOrEnlist() - { - // We're in a transaction - if (Transaction.Current != null) - { - // We haven't yet been called inside of a transaction. So enlist - // in the transaction, and store our save point - if (_enlistedTransaction == null) - { - Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None); - _enlistedTransaction = Transaction.Current; - - _temporaryValue = new StringBuilder(_value.ToString()); - } - // We're already enlisted in a transaction - else - { - // And we're in that transaction - if (Transaction.Current != _enlistedTransaction) - { - throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); - } - } - } - // We're not in a transaction - else - { - // If we're not subscribed to a transaction, modify the underlying value - if (_enlistedTransaction != null) - { - throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); - } - } - } - } -} diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs deleted file mode 100644 index e77ffebedb4..00000000000 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ /dev/null @@ -1,708 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#pragma warning disable 1634, 1691 - -using System.Collections.Generic; -using System.Transactions; -using System.Management.Automation.Internal; - -namespace System.Management.Automation -{ - /// - /// The status of a PowerShell transaction. - /// - public enum PSTransactionStatus - { - /// - /// The transaction has been rolled back. - /// - RolledBack = 0, - - /// - /// The transaction has been committed. - /// - Committed = 1, - - /// - /// The transaction is currently active. - /// - Active = 2 - } - - /// - /// Represents an active transaction. - /// - public sealed class PSTransaction : IDisposable - { - /// - /// Initializes a new instance of the PSTransaction class. - /// - internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - _transaction = new CommittableTransaction(timeout); - RollbackPreference = rollbackPreference; - _subscriberCount = 1; - } - - /// - /// Initializes a new instance of the PSTransaction class using a CommittableTransaction. - /// - internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity) - { - _transaction = transaction; - RollbackPreference = severity; - _subscriberCount = 1; - } - - private CommittableTransaction _transaction; - - /// - /// Gets the rollback preference for this transaction. - /// - public RollbackSeverity RollbackPreference { get; } - - /// - /// Gets the number of subscribers to this transaction. - /// - public int SubscriberCount - { - get - { - // Verify the transaction hasn't been rolled back beneath us - if (this.IsRolledBack) - { - this.SubscriberCount = 0; - } - - return _subscriberCount; - } - - set { _subscriberCount = value; } - } - - private int _subscriberCount; - - /// - /// Returns the status of this transaction. - /// - public PSTransactionStatus Status - { - get - { - if (IsRolledBack) - { - return PSTransactionStatus.RolledBack; - } - else if (IsCommitted) - { - return PSTransactionStatus.Committed; - } - else - { - return PSTransactionStatus.Active; - } - } - } - - /// - /// Activates the transaction held by this PSTransaction. - /// - internal void Activate() - { - Transaction.Current = _transaction; - } - - /// - /// Commits the transaction held by this PSTransaction. - /// - internal void Commit() - { - _transaction.Commit(); - IsCommitted = true; - } - - /// - /// Rolls back the transaction held by this PSTransaction. - /// - internal void Rollback() - { - _transaction.Rollback(); - _isRolledBack = true; - } - - /// - /// Determines whether this PSTransaction has been - /// rolled back or not. - /// - internal bool IsRolledBack - { - get - { - // Check if it's been aborted underneath us - if ( - (!_isRolledBack) && - (_transaction != null) && - (_transaction.TransactionInformation.Status == TransactionStatus.Aborted)) - { - _isRolledBack = true; - } - - return _isRolledBack; - } - - set - { - _isRolledBack = value; - } - } - - private bool _isRolledBack = false; - - /// - /// Determines whether this PSTransaction - /// has been committed or not. - /// - internal bool IsCommitted { get; set; } = false; - - /// - /// Destructor for the PSTransaction class. - /// - ~PSTransaction() - { - Dispose(false); - } - - /// - /// Disposes the PSTransaction object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransaction object, which disposes the - /// underlying transaction. - /// - /// - /// Whether to actually dispose the object. - /// - public void Dispose(bool disposing) - { - if (disposing) - { - if (_transaction != null) - { - _transaction.Dispose(); - } - } - } - } - - /// - /// Supports the transaction management infrastructure for the PowerShell engine. - /// - public sealed class PSTransactionContext : IDisposable - { - /// - /// Initializes a new instance of the PSTransactionManager class. - /// - internal PSTransactionContext(PSTransactionManager transactionManager) - { - _transactionManager = transactionManager; - transactionManager.SetActive(); - } - - private PSTransactionManager _transactionManager; - - /// - /// Destructor for the PSTransactionManager class. - /// - ~PSTransactionContext() - { - Dispose(false); - } - - /// - /// Disposes the PSTransactionContext object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransactionContext object, which resets the - /// active PSTransaction. - /// - /// - /// Whether to actually dispose the object. - /// - private void Dispose(bool disposing) - { - if (disposing) - { - _transactionManager.ResetActive(); - } - } - } - - /// - /// The severity of error that causes PowerShell to automatically - /// rollback the transaction. - /// - public enum RollbackSeverity - { - /// - /// Non-terminating errors or worse. - /// - Error, - - /// - /// Terminating errors or worse. - /// - TerminatingError, - - /// - /// Do not rollback the transaction on error. - /// - Never - } -} - -namespace System.Management.Automation.Internal -{ - /// - /// Supports the transaction management infrastructure for the PowerShell engine. - /// - internal sealed class PSTransactionManager : IDisposable - { - /// - /// Initializes a new instance of the PSTransactionManager class. - /// - internal PSTransactionManager() - { - _transactionStack = new Stack(); - _transactionStack.Push(null); - } - - /// - /// Called by engine APIs to ensure they are protected from - /// ambient transactions. - /// - internal static IDisposable GetEngineProtectionScope() - { - if (s_engineProtectionEnabled && (Transaction.Current != null)) - { - return new System.Transactions.TransactionScope( - System.Transactions.TransactionScopeOption.Suppress); - } - else - { - return null; - } - } - - /// - /// Called by the transaction manager to enable engine - /// protection the first time a transaction is activated. - /// Engine protection APIs remain protected from this point on. - /// - internal static void EnableEngineProtection() - { - s_engineProtectionEnabled = true; - } - - private static bool s_engineProtectionEnabled = false; - - /// - /// Gets the rollback preference for the active transaction. - /// - internal RollbackSeverity RollbackPreference - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActive; - - // This is not an expected condition, and is just protective - // coding. -#pragma warning suppress 56503 - throw new InvalidOperationException(error); - } - - return currentTransaction.RollbackPreference; - } - } - - /// - /// Creates a new Transaction if none are active. Otherwise, increments - /// the subscriber count for the active transaction. - /// - internal void CreateOrJoin() - { - CreateOrJoin(RollbackSeverity.Error, TimeSpan.FromMinutes(1)); - } - - /// - /// Creates a new Transaction if none are active. Otherwise, increments - /// the subscriber count for the active transaction. - /// - internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // There is a transaction on the stack - if (currentTransaction != null) - { - // If you are already in a transaction that has been aborted, or committed, - // create it. - if (currentTransaction.IsRolledBack || currentTransaction.IsCommitted) - { - // Clean up the "used" one - _transactionStack.Pop().Dispose(); - - // And add a new one to the stack - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - else - { - // This is a usable one. Add a subscriber to it. - currentTransaction.SubscriberCount++; - } - } - else - { - // Add a new transaction to the stack - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - } - - /// - /// Creates a new Transaction that should be managed independently of - /// any parent transactions. - /// - internal void CreateNew() - { - CreateNew(RollbackSeverity.Error, TimeSpan.FromMinutes(1)); - } - - /// - /// Creates a new Transaction that should be managed independently of - /// any parent transactions. - /// - internal void CreateNew(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - - /// - /// Completes the current transaction. If only one subscriber is active, this - /// commits the transaction. Otherwise, it reduces the subscriber count by one. - /// - internal void Commit() - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to commit a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActiveForCommit; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted - if (currentTransaction.IsRolledBack) - { - string error = TransactionStrings.TransactionRolledBackForCommit; - throw new TransactionAbortedException(error); - } - - // If you are already in a transaction that has been committed - if (currentTransaction.IsCommitted) - { - string error = TransactionStrings.CommittedTransactionForCommit; - throw new InvalidOperationException(error); - } - - if (currentTransaction.SubscriberCount == 1) - { - currentTransaction.Commit(); - currentTransaction.SubscriberCount = 0; - } - else - { - currentTransaction.SubscriberCount--; - } - - // Now that we've committed, go back to the last available transaction - while ((_transactionStack.Count > 2) && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - } - - /// - /// Aborts the current transaction, no matter how many subscribers are part of it. - /// - internal void Rollback() - { - Rollback(false); - } - - /// - /// Aborts the current transaction, no matter how many subscribers are part of it. - /// - internal void Rollback(bool suppressErrors) - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to roll back a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActiveForRollback; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted - if (currentTransaction.IsRolledBack) - { - if (!suppressErrors) - { - // Otherwise, you should not be able to roll it back. - string error = TransactionStrings.TransactionRolledBackForRollback; - throw new TransactionAbortedException(error); - } - } - - // See if they've already committed the transaction - if (currentTransaction.IsCommitted) - { - if (!suppressErrors) - { - string error = TransactionStrings.CommittedTransactionForRollback; - throw new InvalidOperationException(error); - } - } - - // Roll back the transaction if it hasn't been rolled back - currentTransaction.SubscriberCount = 0; - currentTransaction.Rollback(); - - // Now that we've rolled back, go back to the last available transaction - while ((_transactionStack.Count > 2) && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - } - - /// - /// Sets the base transaction; any transactions created thereafter will be nested to this instance. - /// - internal void SetBaseTransaction(CommittableTransaction transaction, RollbackSeverity severity) - { - if (this.HasTransaction) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionMustBeFirst); - } - - PSTransaction currentTransaction = _transactionStack.Peek(); - - // If there is a "used" transaction at the top of the stack, clean it up - while (_transactionStack.Peek() != null && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - - _baseTransaction = new PSTransaction(transaction, severity); - _transactionStack.Push(_baseTransaction); - } - - /// - /// Removes the transaction added by SetBaseTransaction. - /// - internal void ClearBaseTransaction() - { - if (_baseTransaction == null) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionNotSet); - } - - if (_transactionStack.Peek() != _baseTransaction) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionNotActive); - } - - _transactionStack.Pop().Dispose(); - _baseTransaction = null; - } - - private Stack _transactionStack; - private PSTransaction _baseTransaction; - - /// - /// Returns the current engine transaction. - /// - internal PSTransaction GetCurrent() - { - return _transactionStack.Peek(); - } - - /// - /// Activates the current transaction, both in the engine, and in the Ambient. - /// - internal void SetActive() - { - PSTransactionManager.EnableEngineProtection(); - - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to activate a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionForActivation; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted, you should - // not be able to activate it. - if (currentTransaction.IsRolledBack) - { - string error = TransactionStrings.NoTransactionForActivationBecauseRollback; - throw new TransactionAbortedException(error); - } - - _previousActiveTransaction = Transaction.Current; - currentTransaction.Activate(); - } - - private Transaction _previousActiveTransaction; - - /// - /// Deactivates the current transaction in the engine, and restores the - /// ambient transaction. - /// - internal void ResetActive() - { - // Even if you are in a transaction that has been aborted, you - // should still be able to restore the current transaction. - - Transaction.Current = _previousActiveTransaction; - _previousActiveTransaction = null; - } - - /// - /// Determines if you have a transaction that you can set active and work on. - /// - internal bool HasTransaction - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if ((currentTransaction != null) && - (!currentTransaction.IsCommitted) && - (!currentTransaction.IsRolledBack)) - { - return true; - } - else - { - return false; - } - } - } - - /// - /// Determines if the last transaction has been committed. - /// - internal bool IsLastTransactionCommitted - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction != null) - { - return currentTransaction.IsCommitted; - } - else - { - return false; - } - } - } - - /// - /// Determines if the last transaction has been rolled back. - /// - internal bool IsLastTransactionRolledBack - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction != null) - { - return currentTransaction.IsRolledBack; - } - else - { - return false; - } - } - } - - /// - /// Destructor for the PSTransactionManager class. - /// - ~PSTransactionManager() - { - Dispose(false); - } - - /// - /// Disposes the PSTransactionManager object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransactionContext object, which resets the - /// active PSTransaction. - /// - /// - /// Whether to actually dispose the object. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "baseTransaction", Justification = "baseTransaction should not be disposed since we do not own it - it belongs to the caller")] - public void Dispose(bool disposing) - { - if (disposing) - { - ResetActive(); - - while (_transactionStack.Peek() != null) - { - PSTransaction currentTransaction = _transactionStack.Pop(); - - if (currentTransaction != _baseTransaction) - { - currentTransaction.Dispose(); - } - } - } - } - } -} diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs deleted file mode 100644 index dcce30264ec..00000000000 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - using System; - using System.Collections; - using System.Collections.ObjectModel; - using System.Management.Automation.Runspaces; - - /// - /// Defines a class which allows simple execution of commands from CLR languages. - /// - public class RunspaceInvoke : IDisposable - { - #region constructors - - /// - /// Runspace on which commands are invoked. - /// - private Runspace _runspace; - - /// - /// Create a RunspaceInvoke for invoking commands. This uses - /// a runspace with default PSSnapins. - /// - public RunspaceInvoke() - { - _runspace = RunspaceFactory.CreateRunspace(); - _runspace.Open(); - if (Runspace.DefaultRunspace == null) - { - Runspace.DefaultRunspace = _runspace; - } - } - - /// - /// Create RunspaceInvoke for invoking command in specified - /// runspace. - /// - /// - /// Runspace must be opened state - public RunspaceInvoke(Runspace runspace) - { - if (runspace == null) - { - throw PSTraceSource.NewArgumentNullException("runspace"); - } - - _runspace = runspace; - if (Runspace.DefaultRunspace == null) - { - Runspace.DefaultRunspace = _runspace; - } - } - - #endregion constructors - - #region invoke - - /// - /// Invoke the specified script. - /// - /// PowerShell script to invoke. - /// Output of invocation. - public Collection Invoke(string script) - { - return Invoke(script, null); - } - - /// - /// Invoke the specified script and passes specified input to the script. - /// - /// PowerShell script to invoke. - /// Input to script. - /// Output of invocation. - public Collection Invoke(string script, IEnumerable input) - { - if (_disposed == true) - { - throw PSTraceSource.NewObjectDisposedException("runspace"); - } - - if (script == null) - { - throw PSTraceSource.NewArgumentNullException("script"); - } - - Pipeline p = _runspace.CreatePipeline(script); - return p.Invoke(input); - } - - /// - /// Invoke the specified script and passes specified input to the script. - /// - /// PowerShell script to invoke. - /// Input to script. - /// This gets errors from script. - /// Output of invocation. - /// - /// is the non-terminating error stream - /// from the command. - /// In this release, the objects read from this PipelineReader - /// are PSObjects wrapping ErrorRecords. - /// - public Collection Invoke(string script, IEnumerable input, out IList errors) - { - if (_disposed == true) - { - throw PSTraceSource.NewObjectDisposedException("runspace"); - } - - if (script == null) - { - throw PSTraceSource.NewArgumentNullException("script"); - } - - Pipeline p = _runspace.CreatePipeline(script); - Collection output = p.Invoke(input); - // 2004/06/30-JonN was ReadAll() which was non-blocking - errors = p.Error.NonBlockingRead(); - return output; - } - - #endregion invoke - - #region IDisposable Members - - /// - /// Set to true when object is disposed. - /// - private bool _disposed; - - /// - /// Dispose underlying Runspace. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Protected dispose which can be overridden by derived classes. - /// - /// - protected virtual void Dispose(bool disposing) - { - if (_disposed == false) - { - if (disposing) - { - _runspace.Close(); - _runspace = null; - } - } - - _disposed = true; - } - - #endregion IDisposable Members - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs deleted file mode 100644 index 0f9d302d6e1..00000000000 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Remoting; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2. - /// -#if !CORECLR - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] - [Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210611")] -#endif - [OutputType(typeof(Job))] - public class ResumeJobCommand : JobCmdletBase, IDisposable - { - #region Parameters - /// - /// Specifies the Jobs objects which need to be - /// suspended. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = JobParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Job[] Job - { - get - { - return _jobs; - } - - set - { - _jobs = value; - } - } - - private Job[] _jobs; - - /// - /// - public override string[] Command - { - get - { - return null; - } - } - - /// - /// Specifies whether to delay returning from the cmdlet until all jobs reach a running state. - /// This could take significant time due to workflow throttling. - /// - [Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)] - public SwitchParameter Wait { get; set; } - - #endregion Parameters - - #region Overrides - - /// - /// Resume the Job. - /// - protected override void ProcessRecord() - { - // List of jobs to resume - List jobsToResume = null; - - switch (ParameterSetName) - { - case NameParameterSet: - { - jobsToResume = FindJobsMatchingByName(true, false, true, false); - } - - break; - - case InstanceIdParameterSet: - { - jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); - } - - break; - - case SessionIdParameterSet: - { - jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); - } - - break; - - case StateParameterSet: - { - jobsToResume = FindJobsMatchingByState(false); - } - - break; - - case FilterParameterSet: - { - jobsToResume = FindJobsMatchingByFilter(false); - } - - break; - - default: - { - jobsToResume = CopyJobsToList(_jobs, false, false); - } - - break; - } - - _allJobsToResume.AddRange(jobsToResume); - - // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state - // Setting Wait to true so that this cmdlet will wait for the running job state. - if (_allJobsToResume.Count == 1) - Wait = true; - - foreach (Job job in jobsToResume) - { - var job2 = job as Job2; - - // If the job is not Job2, the resume operation is not supported. - if (job2 == null) - { - WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); - continue; - } - - string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); - if (ShouldProcess(targetString, VerbsLifecycle.Resume)) - { - _cleanUpActions.Add(job2, HandleResumeJobCompleted); - job2.ResumeJobCompleted += HandleResumeJobCompleted; - - lock (_syncObject) - { - if (!_pendingJobs.Contains(job2.InstanceId)) - { - _pendingJobs.Add(job2.InstanceId); - } - } - - job2.ResumeJobAsync(); - } - } - } - - private bool _warnInvalidState = false; - private readonly HashSet _pendingJobs = new HashSet(); - private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); - private readonly Dictionary> _cleanUpActions = - new Dictionary>(); - private readonly List _errorsToWrite = new List(); - private readonly List _allJobsToResume = new List(); - private readonly object _syncObject = new object(); - private bool _needToCheckForWaitingJobs; - - private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) - { - Job job = sender as Job; - - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) - { - _warnInvalidState = true; - } - - var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) - { - foreach ( - var e in - parentJob.ExecutionError.Where(static e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError") - ) - { - if (e.Exception is InvalidJobStateException) - { - // if any errors were invalid job state exceptions, warn the user. - // This is to support Get-Job | Resume-Job scenarios when many jobs - // are Completed, etc. - _warnInvalidState = true; - } - else - { - _errorsToWrite.Add(e); - } - } - - parentJob.ExecutionError.Clear(); - } - - bool releaseWait = false; - lock (_syncObject) - { - if (_pendingJobs.Contains(job.InstanceId)) - { - _pendingJobs.Remove(job.InstanceId); - } - - if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) - releaseWait = true; - } - // end processing has been called - // set waithandle if this is the last one - if (releaseWait) - _waitForJobs.Set(); - } - - /// - /// End Processing. - /// - protected override void EndProcessing() - { - bool jobsPending = false; - lock (_syncObject) - { - _needToCheckForWaitingJobs = true; - if (_pendingJobs.Count > 0) - { - jobsPending = true; - } - } - - if (Wait && jobsPending) - { - _waitForJobs.WaitOne(); - } - - if (_warnInvalidState) - { - WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); - } - - foreach (var e in _errorsToWrite) - { - WriteError(e); - } - - foreach (var j in _allJobsToResume) - { - WriteObject(j); - } - - base.EndProcessing(); - } - - /// - /// - protected override void StopProcessing() - { - _waitForJobs.Set(); - } - - #endregion Overrides - - #region Dispose - - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// - /// - protected void Dispose(bool disposing) - { - if (!disposing) - { - return; - } - - foreach (var pair in _cleanUpActions) - { - pair.Key.ResumeJobCompleted -= pair.Value; - } - - _waitForJobs.Dispose(); - } - #endregion Dispose - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs deleted file mode 100644 index e454247ae9a..00000000000 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Remoting; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// This cmdlet suspends the jobs that are Job2. Errors are added for each Job that is not Job2. - /// -#if !CORECLR - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] - [Cmdlet(VerbsLifecycle.Suspend, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210613")] - [OutputType(typeof(Job))] -#endif - public class SuspendJobCommand : JobCmdletBase, IDisposable - { - #region Parameters - /// - /// Specifies the Jobs objects which need to be - /// suspended. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = JobParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Job[] Job - { - get - { - return _jobs; - } - - set - { - _jobs = value; - } - } - - private Job[] _jobs; - - /// - /// - public override string[] Command - { - get - { - return null; - } - } - - /// - /// If state of the job is running , this will forcefully suspend it. - /// - [Parameter(ParameterSetName = RemoveJobCommand.InstanceIdParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.JobParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.NameParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.SessionIdParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.FilterParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.StateParameterSet)] - [Alias("F")] - public SwitchParameter Force - { - get - { - return _force; - } - - set - { - _force = value; - } - } - - private bool _force = false; - - /// - /// - [Parameter()] - public SwitchParameter Wait - { - get - { - return _wait; - } - - set - { - _wait = value; - } - } - - private bool _wait = false; - - #endregion Parameters - - #region Overrides - - /// - /// Suspend the Job. - /// - protected override void ProcessRecord() - { - // List of jobs to suspend - List jobsToSuspend = null; - - switch (ParameterSetName) - { - case NameParameterSet: - { - jobsToSuspend = FindJobsMatchingByName(true, false, true, false); - } - - break; - - case InstanceIdParameterSet: - { - jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false); - } - - break; - - case SessionIdParameterSet: - { - jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false); - } - - break; - - case StateParameterSet: - { - jobsToSuspend = FindJobsMatchingByState(false); - } - - break; - - case FilterParameterSet: - { - jobsToSuspend = FindJobsMatchingByFilter(false); - } - - break; - - default: - { - jobsToSuspend = CopyJobsToList(_jobs, false, false); - } - - break; - } - - _allJobsToSuspend.AddRange(jobsToSuspend); - - foreach (Job job in jobsToSuspend) - { - var job2 = job as Job2; - - // If the job is not Job2, the suspend operation is not supported. - if (job2 == null) - { - WriteError( - new ErrorRecord( - PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id), - "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); - continue; - } - - string targetString = - PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, - job.Command, job.Id); - if (ShouldProcess(targetString, VerbsLifecycle.Suspend)) - { - if (_wait) - { - _cleanUpActions.Add(job2, HandleSuspendJobCompleted); - } - else - { - if (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Stopping) - { - _warnInvalidState = true; - continue; - } - - if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended) - continue; - - job2.StateChanged += noWait_Job2_StateChanged; - } - - job2.SuspendJobCompleted += HandleSuspendJobCompleted; - - lock (_syncObject) - { - if (!_pendingJobs.Contains(job2.InstanceId)) - { - _pendingJobs.Add(job2.InstanceId); - } - } - - // there could be possibility that the job gets completed before or after the - // subscribing to nowait_job2_statechanged event so checking it again. - if (!_wait && (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended)) - { - this.ProcessExecutionErrorsAndReleaseWaitHandle(job2); - } - - job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob); - } - } - } - - private bool _warnInvalidState = false; - private readonly HashSet _pendingJobs = new HashSet(); - private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); - private readonly Dictionary> _cleanUpActions = - new Dictionary>(); - private readonly List _errorsToWrite = new List(); - private readonly List _allJobsToSuspend = new List(); - private readonly object _syncObject = new object(); - private bool _needToCheckForWaitingJobs; - - private void noWait_Job2_StateChanged(object sender, JobStateEventArgs e) - { - Job job = sender as Job; - - switch (e.JobStateInfo.State) - { - case JobState.Completed: - case JobState.Stopped: - case JobState.Failed: - case JobState.Suspended: - case JobState.Suspending: - this.ProcessExecutionErrorsAndReleaseWaitHandle(job); - break; - } - } - - private void HandleSuspendJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) - { - Job job = sender as Job; - - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) - { - _warnInvalidState = true; - } - - this.ProcessExecutionErrorsAndReleaseWaitHandle(job); - } - - private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job) - { - bool releaseWait = false; - lock (_syncObject) - { - if (_pendingJobs.Contains(job.InstanceId)) - { - _pendingJobs.Remove(job.InstanceId); - } - else - { - // there could be a possibility of race condition where this function is getting called twice - // so if job doesn't present in the _pendingJobs then just return - return; - } - - if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) - releaseWait = true; - } - - if (!_wait) - { - job.StateChanged -= noWait_Job2_StateChanged; - Job2 job2 = job as Job2; - if (job2 != null) - job2.SuspendJobCompleted -= HandleSuspendJobCompleted; - } - - var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) - { - foreach ( - var e in - parentJob.ExecutionError.Where(static e => e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError") - ) - { - if (e.Exception is InvalidJobStateException) - { - // if any errors were invalid job state exceptions, warn the user. - // This is to support Get-Job | Resume-Job scenarios when many jobs - // are Completed, etc. - _warnInvalidState = true; - } - else - { - _errorsToWrite.Add(e); - } - } - } - - // end processing has been called - // set waithandle if this is the last one - if (releaseWait) - _waitForJobs.Set(); - } - - /// - /// End Processing. - /// - protected override void EndProcessing() - { - bool haveToWait = false; - lock (_syncObject) - { - _needToCheckForWaitingJobs = true; - if (_pendingJobs.Count > 0) - { - haveToWait = true; - } - } - - if (haveToWait) - { - _waitForJobs.WaitOne(); - } - - if (_warnInvalidState) - { - WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState); - } - - foreach (var e in _errorsToWrite) - { - WriteError(e); - } - - foreach (var j in _allJobsToSuspend) - { - WriteObject(j); - } - - base.EndProcessing(); - } - - /// - /// - protected override void StopProcessing() - { - _waitForJobs.Set(); - } - - #endregion Overrides - - #region Dispose - - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// - /// - protected void Dispose(bool disposing) - { - if (!disposing) - { - return; - } - - foreach (var pair in _cleanUpActions) - { - pair.Key.SuspendJobCompleted -= pair.Value; - } - - _waitForJobs.Dispose(); - } - #endregion Dispose - } -} diff --git a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs deleted file mode 100644 index 01cef7dce46..00000000000 --- a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#pragma warning disable 1634, 1691 - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System; - using System.Runtime.InteropServices; - using System.Transactions; - using Microsoft.Win32.SafeHandles; - using System.Management.Automation; - - [Guid("79427A2B-F895-40e0-BE79-B57DC82ED231"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IKernelTransaction - { - int GetHandle(out IntPtr pHandle); - } - - [System.Security.SuppressUnmanagedCodeSecurity] - internal sealed class SafeTransactionHandle : SafeHandleZeroOrMinusOneIsInvalid - { - private const string resBaseName = "RegistryProviderStrings"; - - private SafeTransactionHandle(IntPtr handle) - : base(true) - { - this.handle = handle; - } - - internal static SafeTransactionHandle Create() - { - return SafeTransactionHandle.Create(Transaction.Current); - } - - internal static SafeTransactionHandle Create(Transaction managedTransaction) - { - if (managedTransaction == null) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NeedTransaction); - } - - // MSDTC is not available on WinPE machine. - // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface. - // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support - // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc. - // We need KTMRM service as well. WinPE doesn't have these services installed - if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) - { - throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); - } - - IDtcTransaction dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction); - IKernelTransaction ktmInterface = dtcTransaction as IKernelTransaction; - if (ktmInterface == null) - { - throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); - } - - IntPtr ktmTxHandle; - int hr = ktmInterface.GetHandle(out ktmTxHandle); - HandleError(hr); - - return new SafeTransactionHandle(ktmTxHandle); - } - - protected override bool ReleaseHandle() - { - // We don't care about the value of GetLastError. -#pragma warning suppress 56523 - return Win32Native.CloseHandle(this.handle); - } - - private static void HandleError(int error) - { - if (error != Win32Native.ERROR_SUCCESS) - { - throw new System.ComponentModel.Win32Exception(error); - } - } - } -} diff --git a/src/System.Management.Automation/namespaces/TransactedRegistry.cs b/src/System.Management.Automation/namespaces/TransactedRegistry.cs deleted file mode 100644 index 6465ea1819c..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistry.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\Registry.cs. -// Namespace: Microsoft.Win32 -// - -using BCLDebug = System.Diagnostics.Debug; - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System.Runtime.InteropServices; - using System.Runtime.Versioning; - using System.Diagnostics.CodeAnalysis; - - /** - * Registry encapsulation. Contains members representing all top level system - * keys. - * - * @security(checkClassLinking=on) - */ - // This class contains only static members and does not need to be serializable. - [ComVisible(true)] - // Suppressed because these objects need to be accessed from CmdLets. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - internal static class TransactedRegistry - { - private const string resBaseName = "RegistryProviderStrings"; - /** - * Current User Key. - * - * This key should be used as the root for all user specific settings. - */ - /// TransactedRegistry.CurrentUser - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CURRENT_USER. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey CurrentUser = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CURRENT_USER); - - /** - * Local Machine Key. - * - * This key should be used as the root for all machine specific settings. - */ - /// TransactedRegistry.LocalMachine - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_LOCAL_MACHINE. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey LocalMachine = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_LOCAL_MACHINE); - - /** - * Classes Root Key. - * - * This is the root key of class information. - */ - /// TransactedRegistry.ClassesRoot - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CLASSES_ROOT. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey ClassesRoot = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CLASSES_ROOT); - - /** - * Users Root Key. - * - * This is the root of users. - */ - /// TransactedRegistry.Users - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_USERS. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey Users = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_USERS); - - /** - * Current Config Root Key. - * - * This is where current configuration information is stored. - */ - /// TransactedRegistry.CurrentConfig - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CURRENT_CONFIG. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey CurrentConfig = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CURRENT_CONFIG); - } -} diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs deleted file mode 100644 index d899d9257b4..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ /dev/null @@ -1,2057 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\RegistryKey.cs. -// Namespace: Microsoft.Win32 -// -/* - Note on transaction support: - Eventually we will want to add support for NT's transactions to our - TransactedRegistryKey API's (possibly Whidbey M3?). When we do this, here's - the list of API's we need to make transaction-aware: - - RegCreateKeyEx - RegDeleteKey - RegDeleteValue - RegEnumKeyEx - RegEnumValue - RegOpenKeyEx - RegQueryInfoKey - RegQueryValueEx - RegSetValueEx - - We can ignore RegConnectRegistry (remote registry access doesn't yet have - transaction support) and RegFlushKey. RegCloseKey doesn't require any - additional work. . - */ - -/* - Note on ACL support: - The key thing to note about ACL's is you set them on a kernel object like a - registry key, then the ACL only gets checked when you construct handles to - them. So if you set an ACL to deny read access to yourself, you'll still be - able to read with that handle, but not with new handles. - - Another peculiarity is a Terminal Server app compatibility hack. The OS - will second guess your attempt to open a handle sometimes. If a certain - combination of Terminal Server app compat registry keys are set, then the - OS will try to reopen your handle with lesser permissions if you couldn't - open it in the specified mode. So on some machines, we will see handles that - may not be able to read or write to a registry key. It's very strange. But - the real test of these handles is attempting to read or set a value in an - affected registry key. - - For reference, at least two registry keys must be set to particular values - for this behavior: - HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1. - HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1 - There might possibly be an interaction with yet a third registry key as well. - -*/ - -using BCLDebug = System.Diagnostics.Debug; - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System; - using System.Collections.Generic; - using System.Security; - using System.Security.AccessControl; - using System.Security.Permissions; - using System.Text; - using System.IO; - using System.Runtime.InteropServices; - using Microsoft.Win32; - using System.Runtime.Versioning; - using System.Globalization; - using System.Transactions; - using System.Diagnostics.CodeAnalysis; - - // Putting this in a separate internal class to avoid OACR warning DoNotDeclareReadOnlyMutableReferenceTypes. - internal sealed class BaseRegistryKeys - { - // We could use const here, if C# supported ELEMENT_TYPE_I fully. - internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); - internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); - internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); - internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); - internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); - } - - /// - /// Registry encapsulation. To get an instance of a TransactedRegistryKey use the - /// Registry class's static members then call OpenSubKey. - /// - /// @see Registry - /// @security(checkDllCalls=off) - /// @security(checkClassLinking=on) - /// - [ComVisible(true)] - // Suppressed because these objects are written to the pipeline so need to be accessible. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryKey : MarshalByRefObject, IDisposable - { - private const string resBaseName = "RegistryProviderStrings"; - - // Dirty indicates that we have munged data that should be potentially - // written to disk. - // - private const int STATE_DIRTY = 0x0001; - - // SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" - // or "closed". - // - private const int STATE_SYSTEMKEY = 0x0002; - - // Access - // - private const int STATE_WRITEACCESS = 0x0004; - - // Names of keys. This array must be in the same order as the HKEY values listed above. - // - private static readonly string[] s_hkeyNames = new string[] { - "HKEY_CLASSES_ROOT", - "HKEY_CURRENT_USER", - "HKEY_LOCAL_MACHINE", - "HKEY_USERS", - "HKEY_PERFORMANCE_DATA", - "HKEY_CURRENT_CONFIG", - "HKEY_DYN_DATA" - }; - - // MSDN defines the following limits for registry key names & values: - // Key Name: 255 characters - // Value name: Win9x: 255 NT: 16,383 Unicode characters, or 260 ANSI chars - // Value: either 1 MB or current available memory, depending on registry format. - private const int MaxKeyLength = 255; - private const int MaxValueNameLength = 16383; - private const int MaxValueDataLength = 1024 * 1024; - - private SafeRegistryHandle _hkey = null; - private int _state = 0; - private string _keyName; - private RegistryKeyPermissionCheck _checkMode; - private System.Transactions.Transaction _myTransaction; - private SafeTransactionHandle _myTransactionHandle; - - // This is a wrapper around RegOpenKeyTransacted that implements a workaround - // to TxF bug number 181242 After calling RegOpenKeyTransacted, it calls RegQueryInfoKey. - // If that call fails with ERROR_INVALID_TRANSACTION, we have possibly run into bug 181242. To workaround - // this, we open the key without a transaction and then open it again with - // a transaction and return THAT hkey. - private int RegOpenKeyTransactedWrapper(SafeRegistryHandle hKey, string lpSubKey, - int ulOptions, int samDesired, out SafeRegistryHandle hkResult, - SafeTransactionHandle hTransaction, IntPtr pExtendedParameter) - { - int error = Win32Native.ERROR_SUCCESS; - SafeRegistryHandle hKeyToReturn = null; - - error = Win32Native.RegOpenKeyTransacted(_hkey, lpSubKey, ulOptions, samDesired, out hKeyToReturn, hTransaction, pExtendedParameter); - - if (Win32Native.ERROR_SUCCESS == error && !hKeyToReturn.IsInvalid) - { - // This is a check and workaround for TxR bug 181242. If we try to use the transacted hKey we just opened - // for a call to RegQueryInfoKey and get back a ERROR_INVALID_TRANSACTION error, then the key might be a symbolic link and TxR didn't - // do the open correctly. The workaround is to open it non-transacted, then open it again transacted without - // a subkey string. If we get some error other than ERROR_INVALID_TRANSACTION from RegQueryInfoKey, just ignore it for now. - int subkeyCount = 0; - int valueCount = 0; - error = Win32Native.RegQueryInfoKey(hKeyToReturn, - null, - null, - Win32Native.NULL, - ref subkeyCount, // subkeys - null, - null, - ref valueCount, // values - null, - null, - null, - null); - if (Win32Native.ERROR_INVALID_TRANSACTION == error) - { - SafeRegistryHandle nonTxKey = null; - SafeRegistryHandle txKey = null; - error = Win32Native.RegOpenKeyEx(_hkey, lpSubKey, ulOptions, samDesired, out nonTxKey); - // If we got some error on this open, just ignore it and continue on with the handle - // we got on the original RegOpenKeyTransacted. - if (Win32Native.ERROR_SUCCESS == error) - { - // Now do an RegOpenKeyTransacted with the non-transacted key and no "subKey" parameter. - error = Win32Native.RegOpenKeyTransacted(nonTxKey, null, ulOptions, samDesired, out txKey, hTransaction, pExtendedParameter); - if (Win32Native.ERROR_SUCCESS == error) - { - // Let's use this hkey instead. - hKeyToReturn.Dispose(); - hKeyToReturn = txKey; - } - - nonTxKey.Dispose(); - nonTxKey = null; - } - } - } - - hkResult = hKeyToReturn; - return error; - } - - /** - * Creates a TransactedRegistryKey. - * - * This key is bound to hkey, if writable is false then no write operations - * will be allowed. If systemkey is set then the hkey won't be released - * when the object is GC'ed. - */ - private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, - System.Transactions.Transaction transaction, SafeTransactionHandle txHandle) - { - _hkey = hkey; - _keyName = string.Empty; - if (systemkey) - { - _state |= STATE_SYSTEMKEY; - } - - if (writable) - { - _state |= STATE_WRITEACCESS; - } - // We want to take our own clone so we can dispose it when we want and - // aren't susceptible to the caller disposing it. - if (transaction != null) - { - _myTransaction = transaction.Clone(); - _myTransactionHandle = txHandle; - } - else - { - _myTransaction = null; - _myTransactionHandle = null; - } - } - - private SafeTransactionHandle GetTransactionHandle() - { - SafeTransactionHandle safeTransactionHandle = null; - - // If myTransaction is not null and is not the same as Transaction.Current - // this is an invalid operation. The transaction within which the RegistryKey object was created - // needs to be the same as the transaction being used now. - if (_myTransaction != null) - { - if (!_myTransaction.Equals(Transaction.Current)) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); - } - else - { - safeTransactionHandle = _myTransactionHandle; - } - } - else // we want to use Transaction.Current for the transaction. - { - safeTransactionHandle = SafeTransactionHandle.Create(); - } - - return safeTransactionHandle; - } - - /// TransactedRegistryKey.Close - /// Closes this key, flushes it to disk if the contents have been modified. - /// Utilizes Transaction.Current for its transaction. - /// - public void Close() - { - Dispose(true); - } - - private void Dispose(bool disposing) - { - if (_hkey != null) - { - if (!IsSystemKey()) - { - try - { - _hkey.Dispose(); - } - catch (IOException) - { - // we don't really care if the handle is invalid at this point - } - finally - { - _hkey = null; - } - } - } - - if (_myTransaction != null) - { - // Dispose the transaction because we cloned it. - try - { - _myTransaction.Dispose(); - } - catch (TransactionException) - { - // ignore. - } - finally - { - _myTransaction = null; - } - } - } - - /// TransactedRegistryKey.Flush - /// Flushes this key. Utilizes Transaction.Current for its transaction. - /// - public void Flush() - { - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - if (_hkey != null) - { - if (IsDirty()) - { - int ret = Win32Native.RegFlushKey(_hkey); - if (Win32Native.ERROR_SUCCESS != ret) - { - throw new IOException(Win32Native.GetMessage(ret), ret); - } - } - } - } - - /// TransactedRegistryKey.Dispose - /// Disposes this key. Utilizes Transaction.Current for its transaction. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey CreateSubKey(string subkey) - { - return CreateSubKey(subkey, _checkMode); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that - /// specifies whether the key is opened for read or read/write access. - [ComVisible(false)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck) - { - return CreateSubKeyInternal(subkey, permissionCheck, (TransactedRegistrySecurity)null); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that - /// specifies whether the key is opened for read or read/write access. - /// A TransactedRegistrySecurity object that specifies the access control security for the new key. - [ComVisible(false)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public unsafe TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, TransactedRegistrySecurity registrySecurity) - { - return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity); - } - - [ComVisible(false)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj) - { - ValidateKeyName(subkey); - // RegCreateKeyTransacted requires a non-empty key name, so let's deal with that here. - if (string.Empty == subkey) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrEmpty); - } - - ValidateKeyMode(permissionCheck); - EnsureWriteable(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - - // only keys opened under read mode is not writable - TransactedRegistryKey existingKey = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); - if (existingKey != null) - { // Key already exits - CheckSubKeyWritePermission(subkey); - CheckSubTreePermission(subkey, permissionCheck); - existingKey._checkMode = permissionCheck; - return existingKey; - } - - CheckSubKeyCreatePermission(subkey); - - Win32Native.SECURITY_ATTRIBUTES secAttrs = null; - TransactedRegistrySecurity registrySecurity = registrySecurityObj as TransactedRegistrySecurity; - // For ACL's, get the security descriptor from the RegistrySecurity. - if (registrySecurity != null) - { - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm(); - // We allocate memory on the stack to improve the speed. - // So this part of code can't be refactored into a method. - byte* pSecDescriptor = stackalloc byte[sd.Length]; - Microsoft.PowerShell.Commands.Internal.Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length); - secAttrs.pSecurityDescriptor = pSecDescriptor; - } - - int disposition = 0; - - // By default, the new key will be writable. - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = Win32Native.RegCreateKeyTransacted(_hkey, - subkey, - 0, - null, - 0, - GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), - secAttrs, - out result, - out disposition, - safeTransactionHandle, - IntPtr.Zero - ); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, - Transaction.Current, safeTransactionHandle); - CheckSubTreePermission(subkey, permissionCheck); - key._checkMode = permissionCheck; - - if (subkey.Length == 0) - key._keyName = _keyName; - else - key._keyName = _keyName + "\\" + subkey; - return key; - } - else if (ret != 0) // syscall failed, ret is an error code. - Win32Error(ret, _keyName + "\\" + subkey); // Access denied? - - BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey"); - return null; - } - - /// - /// Deletes the specified subkey. Will throw an exception if the subkey has - /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. - /// Utilizes Transaction.Current for its transaction. - /// Thrown if the subkey as child subkeys. - /// - /// The subkey to delete. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKey(string subkey) - { - DeleteSubKey(subkey, true); - } - - /// - /// Deletes the specified subkey. Will throw an exception if the subkey has - /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. - /// Utilizes Transaction.Current for its transaction. - /// Thrown if the subkey as child subkeys. - /// Thrown if true is specified for throwOnMissingSubKey and the - /// specified subkey does not exist. - /// - /// The subkey to delete. - /// Specify true if an ArgumentException should be thrown if - /// the specified subkey does not exist. If false is specified, a missing subkey does not throw - /// an exception. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) - { - ValidateKeyName(subkey); - EnsureWriteable(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - CheckSubKeyWritePermission(subkey); - - // Open the key we are deleting and check for children. Be sure to - // explicitly call close to avoid keeping an extra HKEY open. - // - TransactedRegistryKey key = InternalOpenSubKey(subkey, false); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_RegRemoveSubKey); - } - } - finally - { - key.Close(); - } - - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - - if (ret != 0) - { - if (ret == Win32Native.ERROR_FILE_NOT_FOUND) - { - if (throwOnMissingSubKey) - { - throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); - } - } - else - Win32Error(ret, null); - } - } - else - { // there is no key which also means there is no subkey - if (throwOnMissingSubKey) - throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); - } - } - - /// - /// Recursively deletes a subkey and any child subkeys. - /// Utilizes Transaction.Current for its transaction. - /// - /// The subkey to delete. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKeyTree(string subkey) - { - ValidateKeyName(subkey); - - // Security concern: Deleting a hive's "" subkey would delete all - // of that hive's contents. Don't allow "". - if ((string.IsNullOrEmpty(subkey) || subkey.Length == 0) && IsSystemKey()) - { - throw new ArgumentException(RegistryProviderStrings.ArgRegKeyDelHive); - } - - EnsureWriteable(); - - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - CheckSubTreeWritePermission(subkey); - - TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - string[] keys = key.InternalGetSubKeyNames(); - - for (int i = 0; i < keys.Length; i++) - { - key.DeleteSubKeyTreeInternal(keys[i]); - } - } - } - finally - { - key.Close(); - } - - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) - { - Win32Error(ret, null); - } - } - else - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent); - } - } - - // An internal version which does no security checks or argument checking. Skipping the - // security checks should give us a slight perf gain on large trees. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void DeleteSubKeyTreeInternal(string subkey) - { - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - string[] keys = key.InternalGetSubKeyNames(); - - for (int i = 0; i < keys.Length; i++) - { - key.DeleteSubKeyTreeInternal(keys[i]); - } - } - } - finally - { - key.Close(); - } - - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) - { - Win32Error(ret, null); - } - } - else - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent); - } - } - - /// - /// Deletes the specified value from this key. - /// Utilizes Transaction.Current for its transaction. - /// - /// Name of the value to delete. - public void DeleteValue(string name) - { - DeleteValue(name, true); - } - - /// - /// Deletes the specified value from this key. - /// Utilizes Transaction.Current for its transaction. - /// - /// Name of the value to delete. - /// Specify true if an ArgumentException should be thrown if - /// the specified value does not exist. If false is specified, a missing value does not throw - /// an exception. - public void DeleteValue(string name, bool throwOnMissingValue) - { - EnsureWriteable(); - CheckValueWritePermission(name); - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - int errorCode = Win32Native.RegDeleteValue(_hkey, name); - - // - // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE - // This still means the name doesn't exist. We need to be consistent with previous OS. - // - if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) - { - if (throwOnMissingValue) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyValueAbsent); - } - else - { - errorCode = Win32Native.ERROR_SUCCESS; - } - } - - if (Win32Native.ERROR_SUCCESS != errorCode) - { - Win32Error(errorCode, null); - } - } - - /** - * Retrieves a new TransactedRegistryKey that represents the requested key. Valid - * values are: - * - * HKEY_CLASSES_ROOT, - * HKEY_CURRENT_USER, - * HKEY_LOCAL_MACHINE, - * HKEY_USERS, - * HKEY_PERFORMANCE_DATA, - * HKEY_CURRENT_CONFIG, - * HKEY_DYN_DATA. - * - * @param hKey HKEY_* to open. - * - * @return the TransactedRegistryKey requested. - */ - internal static TransactedRegistryKey GetBaseKey(IntPtr hKey) - { - int index = ((int)hKey) & 0x0FFFFFFF; - BCLDebug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!"); - BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!"); - - SafeRegistryHandle srh = new SafeRegistryHandle(hKey, false); - - // For Base keys, there is no transaction associated with the HKEY. - TransactedRegistryKey key = new TransactedRegistryKey(srh, true, true, null, null); - key._checkMode = RegistryKeyPermissionCheck.Default; - key._keyName = s_hkeyNames[index]; - return key; - } - - /// - /// Retrieves a subkey. If readonly is true, then the subkey is opened with - /// read-only access. - /// Utilizes Transaction.Current for its transaction. - /// - /// The subkey requested or null if the operation failed. - /// Name or path of the subkey to open. - /// Set to true of you only need readonly access. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, bool writable) - { - ValidateKeyName(name); - EnsureNotDisposed(); - name = FixupName(name); // Fixup multiple slashes to a single slash - - CheckOpenSubKeyPermission(name, writable); - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, GetRegistryKeyAccess(writable), out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); - key._checkMode = GetSubKeyPermissionCheck(writable); - key._keyName = _keyName + "\\" + name; - return key; - } - - // Return null if we didn't find the key. - if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) - { - // We need to throw SecurityException here for compatibility reasons, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - - return null; - } - - /// - /// Retrieves a subkey. - /// Utilizes Transaction.Current for its transaction. - /// - /// The subkey requested or null if the operation failed. - /// Name or path of the subkey to open. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies - /// whether the key is opened for read or read/write access. - [ComVisible(false)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck) - { - ValidateKeyMode(permissionCheck); - return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)); - } - - /// - /// Retrieves a subkey. - /// Utilizes Transaction.Current for its transaction. - /// - /// The subkey requested or null if the operation failed. - /// Name or path of the subkey to open. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies - /// whether the key is opened for read or read/write access. - /// A bitwise combination of Microsoft.Win32.RegistryRights values that specifies the desired security access. - [ComVisible(false)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) - { - return InternalOpenSubKey(name, permissionCheck, (int)rights); - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private TransactedRegistryKey InternalOpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, int rights) - { - ValidateKeyName(name); - ValidateKeyMode(permissionCheck); - ValidateKeyRights(rights); - EnsureNotDisposed(); - name = FixupName(name); // Fixup multiple slashes to a single slash - - CheckOpenSubKeyPermission(name, permissionCheck); - SafeRegistryHandle result = null; - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, - Transaction.Current, safeTransactionHandle); - key._keyName = _keyName + "\\" + name; - key._checkMode = permissionCheck; - return key; - } - - // Return null if we didn't find the key. - if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) - { - // We need to throw SecurityException here for compatibility reason, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - - return null; - } - - // This required no security checks. This is to get around the Deleting SubKeys which only require - // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal TransactedRegistryKey InternalOpenSubKey(string name, bool writable) - { - ValidateKeyName(name); - EnsureNotDisposed(); - - int winAccess = GetRegistryKeyAccess(writable); - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, winAccess, out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); - key._keyName = _keyName + "\\" + name; - return key; - } - - return null; - } - - /// - /// Retrieves a subkey for readonly access. - /// Utilizes Transaction.Current for its transaction. - /// - /// The subkey requested or null if the operation failed. - /// Name or path of the subkey to open. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name) - { - return OpenSubKey(name, false); - } - - /// - /// Retrieves the count of subkeys. - /// Utilizes Transaction.Current for its transaction. - /// - /// The count of subkeys. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public int SubKeyCount - { - get - { - CheckKeyReadPermission(); - return InternalSubKeyCount(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal int InternalSubKeyCount() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - - int subkeys = 0; - int junk = 0; - int ret = Win32Native.RegQueryInfoKey(_hkey, - null, - null, - Win32Native.NULL, - ref subkeys, // subkeys - null, - null, - ref junk, // values - null, - null, - null, - null); - - if (ret != 0) - Win32Error(ret, null); - return subkeys; - } - - /// - /// Retrieves an array of strings containing all the subkey names. - /// Utilizes Transaction.Current for its transaction. - /// - /// A string array containing all the subkey names. - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public string[] GetSubKeyNames() - { - CheckKeyReadPermission(); - return InternalGetSubKeyNames(); - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal string[] InternalGetSubKeyNames() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - int subkeys = InternalSubKeyCount(); - string[] names = new string[subkeys]; // Returns 0-length array if empty. - - if (subkeys > 0) - { - StringBuilder name = new StringBuilder(256); - int namelen; - - for (int i = 0; i < subkeys; i++) - { - namelen = name.Capacity; // Don't remove this. The API's doesn't work if this is not properly initialised. - int ret = Win32Native.RegEnumKeyEx(_hkey, - i, - name, - out namelen, - null, - null, - null, - null); - if (ret != 0) - Win32Error(ret, null); - names[i] = name.ToString(); - } - } - - return names; - } - - /// - /// Retrieves the count of values. - /// Utilizes Transaction.Current for its transaction. - /// - /// A count of values. - public int ValueCount - { - get - { - CheckKeyReadPermission(); - return InternalValueCount(); - } - } - - internal int InternalValueCount() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - int values = 0; - int junk = 0; - int ret = Win32Native.RegQueryInfoKey(_hkey, - null, - null, - Win32Native.NULL, - ref junk, // subkeys - null, - null, - ref values, // values - null, - null, - null, - null); - if (ret != 0) - Win32Error(ret, null); - return values; - } - - /// - /// Retrieves an array of strings containing all the value names. - /// Utilizes Transaction.Current for its transaction. - /// - /// All the value names. - public string[] GetValueNames() - { - CheckKeyReadPermission(); - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - - int values = InternalValueCount(); - string[] names = new string[values]; - - if (values > 0) - { - StringBuilder name = new StringBuilder(256); - int namelen; - int currentlen; - int ret; - - for (int i = 0; i < values; i++) - { - currentlen = name.Capacity; - ret = Win32Native.ERROR_MORE_DATA; - - // loop while we get error_more_data or until we have exceeded - // the max name length. - while (Win32Native.ERROR_MORE_DATA == ret) - { - namelen = currentlen; - ret = Win32Native.RegEnumValue(_hkey, - i, - name, - ref namelen, - Win32Native.NULL, - null, - null, - null); - - if (ret != 0) - { - if (ret != Win32Native.ERROR_MORE_DATA) - Win32Error(ret, null); - - // We got ERROR_MORE_DATA. Let's see if we can make the buffer - // bigger. - if (MaxValueNameLength == currentlen) - Win32Error(ret, null); - - currentlen = currentlen * 2; - if (MaxValueNameLength < currentlen) - currentlen = MaxValueNameLength; - - // Allocate a new buffer. - name = new StringBuilder(currentlen); - } - } - - names[i] = name.ToString(); - } - } - - return names; - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// - /// The data associated with the value. - /// Name of value to retrieve. - public object GetValue(string name) - { - CheckValueReadPermission(name); - return InternalGetValue(name, null, false, true); - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// - /// The data associated with the value. - /// Name of value to retrieve. - /// Value to return if name doesn't exist. - public object GetValue(string name, object defaultValue) - { - CheckValueReadPermission(name); - return InternalGetValue(name, defaultValue, false, true); - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// - /// The data associated with the value. - /// Name of value to retrieve. - /// Value to return if name doesn't exist. - /// One of the Microsoft.Win32.RegistryValueOptions values that specifies - /// optional processing of the retrieved value. - [ComVisible(false)] - public object GetValue(string name, object defaultValue, RegistryValueOptions options) - { - if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) - { - string resourceTemplate = RegistryProviderStrings.Arg_EnumIllegalVal; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, options.ToString()); - throw new ArgumentException(resource); - } - - bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); - CheckValueReadPermission(name); - return InternalGetValue(name, defaultValue, doNotExpand, true); - } - - internal object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity) - { - if (checkSecurity) - { - // Name can be null! It's the most common use of RegQueryValueEx - EnsureNotDisposed(); - } - - // Don't require a transaction. We don't want to throw for "Base" keys. - - object data = defaultValue; - int type = 0; - int datasize = 0; - - int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - - if (ret != 0) - { - // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data). - // Some OS's returned ERROR_MORE_DATA even in success cases, so we - // want to continue on through the function. - if (ret != Win32Native.ERROR_MORE_DATA) - return data; - } - - switch (type) - { - case Win32Native.REG_DWORD_BIG_ENDIAN: - case Win32Native.REG_BINARY: - { - byte[] blob = new byte[datasize]; - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - data = blob; - } - - break; - case Win32Native.REG_QWORD: - { // also REG_QWORD_LITTLE_ENDIAN - if (datasize > 8) - { - // prevent an AV in the edge case that datasize is larger than sizeof(long) - goto case Win32Native.REG_BINARY; - } - - long blob = 0; - BCLDebug.Assert(datasize == 8, "datasize==8"); - // Here, datasize must be 8 when calling this - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); - - data = blob; - } - - break; - case Win32Native.REG_DWORD: - { // also REG_DWORD_LITTLE_ENDIAN - if (datasize > 4) - { - // prevent an AV in the edge case that datasize is larger than sizeof(int) - goto case Win32Native.REG_QWORD; - } - - int blob = 0; - BCLDebug.Assert(datasize == 4, "datasize==4"); - // Here, datasize must be four when calling this - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); - - data = blob; - } - - break; - - case Win32Native.REG_SZ: - { - StringBuilder blob = new StringBuilder(datasize / 2); - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - data = blob.ToString(); - } - - break; - - case Win32Native.REG_EXPAND_SZ: - { - StringBuilder blob = new StringBuilder(datasize / 2); - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - if (doNotExpand) - data = blob.ToString(); - else - data = Environment.ExpandEnvironmentVariables(blob.ToString()); - } - - break; - case Win32Native.REG_MULTI_SZ: - { - IList strings = new List(); - - char[] blob = new char[datasize / 2]; - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - - int cur = 0; - int len = blob.Length; - - while (ret == 0 && cur < len) - { - int nextNull = cur; - while (nextNull < len && blob[nextNull] != (char)0) - { - nextNull++; - } - - if (nextNull < len) - { - BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); - if (nextNull - cur > 0) - { - strings.Add(new string(blob, cur, nextNull - cur)); - } - else - { - // we found an empty string. But if we're at the end of the data, - // it's just the extra null terminator. - if (nextNull != len - 1) - strings.Add(string.Empty); - } - } - else - { - strings.Add(new string(blob, cur, len - cur)); - } - - cur = nextNull + 1; - } - - data = new string[strings.Count]; - strings.CopyTo((string[])data, 0); - // data = strings.GetAllItems(String.class); - } - - break; - case Win32Native.REG_NONE: - case Win32Native.REG_LINK: - default: - break; - } - - return data; - } - - /// - /// Retrieves the registry data type of the value associated with the specified name. - /// Utilizes Transaction.Current for its transaction. - /// - /// A RegistryValueKind value representing the registry data type of the value associated with name. - /// The value name whose data type is to be retrieved. - [ComVisible(false)] - public RegistryValueKind GetValueKind(string name) - { - CheckValueReadPermission(name); - EnsureNotDisposed(); - - int type = 0; - int datasize = 0; - int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - if (ret != 0) - Win32Error(ret, null); - - if (!Enum.IsDefined(typeof(RegistryValueKind), type)) - return RegistryValueKind.Unknown; - else - return (RegistryValueKind)type; - } - - /** - * Retrieves the current state of the dirty property. - * - * A key is marked as dirty if any operation has occurred that modifies the - * contents of the key. - * - * @return true if the key has been modified. - */ - private bool IsDirty() - { - return (_state & STATE_DIRTY) != 0; - } - - private bool IsSystemKey() - { - return (_state & STATE_SYSTEMKEY) != 0; - } - - private bool IsWritable() - { - return (_state & STATE_WRITEACCESS) != 0; - } - - /// - /// Retrieves the name of the key. - /// - /// The name of the key. - public string Name - { - get - { - EnsureNotDisposed(); - return _keyName; - } - } - - private void SetDirty() - { - _state |= STATE_DIRTY; - } - - /// - /// Sets the specified value. Utilizes Transaction.Current for its transaction. - /// - /// Name of value to store data in. - /// Data to store. - public void SetValue(string name, object value) - { - SetValue(name, value, RegistryValueKind.Unknown); - } - - /// - /// Sets the specified value. Utilizes Transaction.Current for its transaction. - /// - /// Name of value to store data in. - /// Data to store. - /// The registry data type to use when storing the data. - [ComVisible(false)] - public unsafe void SetValue(string name, object value, RegistryValueKind valueKind) - { - ArgumentNullException.ThrowIfNull(value, RegistryProviderStrings.Arg_Value); - - if (name != null && name.Length > MaxValueNameLength) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegValueNameStrLenBug); - } - - if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) - throw new ArgumentException(RegistryProviderStrings.Arg_RegBadKeyKind); - - EnsureWriteable(); - - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - - if (ContainsRegistryValue(name)) - { // Existing key - CheckValueWritePermission(name); - } - else - { // Creating a new value - CheckValueCreatePermission(name); - } - - if (valueKind == RegistryValueKind.Unknown) - { - // this is to maintain compatibility with the old way of autodetecting the type. - // SetValue(string, object) will come through this codepath. - valueKind = CalculateValueKind(value); - } - - int ret = 0; - try - { - switch (valueKind) - { - case RegistryValueKind.ExpandString: - case RegistryValueKind.String: - { - string data = value.ToString(); - // divide by 2 to account for unicode. - if (MaxValueDataLength / 2 < data.Length) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - valueKind, - data, - data.Length * 2 + 2); - break; - } - - case RegistryValueKind.MultiString: - { - // Other thread might modify the input array after we calculate the buffer length. - // Make a copy of the input array to be safe. - string[] dataStrings = (string[])(((string[])value).Clone()); - - int sizeInBytes = 0; - - // First determine the size of the array - // - for (int i = 0; i < dataStrings.Length; i++) - { - if (dataStrings[i] == null) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetStrArrNull); - } - - sizeInBytes += (dataStrings[i].Length + 1) * 2; - } - - sizeInBytes += 2; - - if (MaxValueDataLength < sizeInBytes) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - byte[] basePtr = new byte[sizeInBytes]; - fixed (byte* b = basePtr) - { - int totalBytesMoved = 0; - int currentBytesMoved = 0; - - // Write out the strings... - // - for (int i = 0; i < dataStrings.Length; i++) - { - currentBytesMoved = System.Text.Encoding.Unicode.GetBytes(dataStrings[i], 0, dataStrings[i].Length, basePtr, totalBytesMoved); - totalBytesMoved += currentBytesMoved; - basePtr[totalBytesMoved] = 0; - basePtr[totalBytesMoved + 1] = 0; - totalBytesMoved += 2; - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.MultiString, - basePtr, - sizeInBytes); - } - - break; - } - - case RegistryValueKind.Binary: - byte[] dataBytes = (byte[])value; - if (MaxValueDataLength < dataBytes.Length) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.Binary, - dataBytes, - dataBytes.Length); - break; - - case RegistryValueKind.DWord: - { - // We need to use Convert here because we could have a boxed type cannot be - // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail. - int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture); - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.DWord, - ref data, - 4); - break; - } - - case RegistryValueKind.QWord: - { - long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture); - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.QWord, - ref data, - 8); - break; - } - } - } - catch (OverflowException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (InvalidOperationException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (FormatException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (InvalidCastException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - - if (ret == 0) - { - SetDirty(); - } - else - Win32Error(ret, null); - } - - private RegistryValueKind CalculateValueKind(object value) - { - // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. - // Even though we could add detection for an int64 in here, we want to maintain compatibility with the - // old behavior. - if (value is Int32) - return RegistryValueKind.DWord; - else if (value is Array) - { - if (value is byte[]) - return RegistryValueKind.Binary; - else if (value is string[]) - return RegistryValueKind.MultiString; - else - { - string resourceTemplate = RegistryProviderStrings.Arg_RegSetBadArrType; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, value.GetType().Name); - throw new ArgumentException(resource); - } - } - else - return RegistryValueKind.String; - } - - /** - * Retrieves a string representation of this key. - * - * @return a string representing the key. - */ - /// - /// Retrieves a string representation of this key. - /// - /// A string representing the key. - public override string ToString() - { - EnsureNotDisposed(); - return _keyName; - } - - /// - /// Returns the access control security for the current registry key. - /// Utilizes Transaction.Current for its transaction. - /// - /// A TransactedRegistrySecurity object that describes the access control - /// permissions on the registry key represented by the current TransactedRegistryKey. - public TransactedRegistrySecurity GetAccessControl() - { - return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - /// - /// Returns the access control security for the current registry key. - /// Utilizes Transaction.Current for its transaction. - /// - /// A TransactedRegistrySecurity object that describes the access control - /// permissions on the registry key represented by the current TransactedRegistryKey. - /// A bitwise combination of AccessControlSections values that specifies the type of security information to get. - public TransactedRegistrySecurity GetAccessControl(AccessControlSections includeSections) - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - return new TransactedRegistrySecurity(_hkey, _keyName, includeSections); - } - - /// - /// Applies Windows access control security to an existing registry key. - /// Utilizes Transaction.Current for its transaction. - /// - /// A TransactedRegistrySecurity object that specifies the access control security to apply to the current subkey. - public void SetAccessControl(TransactedRegistrySecurity registrySecurity) - { - EnsureWriteable(); - ArgumentNullException.ThrowIfNull(registrySecurity); - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - - registrySecurity.Persist(_hkey, _keyName); - } - - /** - * After calling GetLastWin32Error(), it clears the last error field, - * so you must save the HResult and pass it to this method. This method - * will determine the appropriate exception to throw dependent on your - * error, and depending on the error, insert a string into the message - * gotten from the ResourceManager. - */ - internal void Win32Error(int errorCode, string str) - { - switch (errorCode) - { - case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) - { - string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); - throw new UnauthorizedAccessException(resource); - } - else - throw new UnauthorizedAccessException(); - - case Win32Native.ERROR_INVALID_HANDLE: - // ** - // * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException. - // * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the - // * SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues - // * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception - // * on reentrant calls because of this error code path in RegistryKey - // * - // * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this, - // * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on - // * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of - // * having serialized access). - // * - // * FUTURE: Consider changing PerformanceCounterLib to handle its own Win32 RegistryKey API calls instead of depending - // * on Microsoft.Win32.RegistryKey, so that RegistryKey can be clean of special-cases for HKEY_PERFORMANCE_DATA. - // - _hkey.SetHandleAsInvalid(); - _hkey = null; - goto default; - - case Win32Native.ERROR_FILE_NOT_FOUND: - { - string resourceTemplate = RegistryProviderStrings.Arg_RegKeyNotFound; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, errorCode.ToString(System.Globalization.CultureInfo.InvariantCulture)); - throw new IOException(resource); - } - - default: - throw new IOException(Win32Native.GetMessage(errorCode), errorCode); - } - } - - internal static void Win32ErrorStatic(int errorCode, string str) - { - switch (errorCode) - { - case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) - { - string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); - throw new UnauthorizedAccessException(resource); - } - else - throw new UnauthorizedAccessException(); - - default: - throw new IOException(Win32Native.GetMessage(errorCode), errorCode); - } - } - - internal static string FixupName(string name) - { - BCLDebug.Assert(name != null, "[FixupName]name!=null"); - if (name.Contains('\\')) - return name; - - StringBuilder sb = new StringBuilder(name); - FixupPath(sb); - int temp = sb.Length - 1; - if (sb[temp] == '\\') // Remove trailing slash - sb.Length = temp; - return sb.ToString(); - } - - private static void FixupPath(StringBuilder path) - { - int length = path.Length; - bool fixup = false; - char markerChar = (char)0xFFFF; - - int i = 1; - while (i < length - 1) - { - if (path[i] == '\\') - { - i++; - while (i < length) - { - if (path[i] == '\\') - { - path[i] = markerChar; - i++; - fixup = true; - } - else - break; - } - } - - i++; - } - - if (fixup) - { - i = 0; - int j = 0; - while (i < length) - { - if (path[i] == markerChar) - { - i++; - continue; - } - - path[j] = path[i]; - i++; - j++; - } - - path.Length += j - i; - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void CheckOpenSubKeyPermission(string subkeyName, bool subKeyWritable) - { - // If the parent key is not opened under default mode, we have access already. - // If the parent key is opened under default mode, we need to check for permission. - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubKeyReadPermission(subkeyName); - } - - if (subKeyWritable && (_checkMode == RegistryKeyPermissionCheck.ReadSubTree)) - { - CheckSubTreeReadWritePermission(subkeyName); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck) - { - if (subKeyCheck == RegistryKeyPermissionCheck.Default) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubKeyReadPermission(subkeyName); - } - } - - CheckSubTreePermission(subkeyName, subKeyCheck); - } - - private void CheckSubTreePermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck) - { - if (subKeyCheck == RegistryKeyPermissionCheck.ReadSubTree) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubTreeReadPermission(subkeyName); - } - } - else if (subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree) - { - if (_checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree) - { - CheckSubTreeReadWritePermission(subkeyName); - } - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyWritePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // If we want to open a subkey of a read-only key as writeable, we need to do the check. - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyReadPermission(string subkeyName) - { - BCLDebug.Assert(_checkMode == RegistryKeyPermissionCheck.Default, "Should be called from a key opened under default mode only!"); - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyCreatePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeReadPermission(string subkeyName) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\").Demand(); - } - } - - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeWritePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\").Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeReadWritePermission(string subkeyName) - { - // If we want to open a subkey of a read-only key as writeable, we need to do the check. - new RegistryPermission(RegistryPermissionAccess.Write | RegistryPermissionAccess.Read, - _keyName + "\\" + subkeyName).Demand(); - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueWritePermission(string valueName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!"); - // skip the security check if the key is opened under write mode - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueCreatePermission(string valueName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating value under read-only key!"); - // skip the security check if the key is opened under write mode - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueReadPermission(string valueName) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // only need to check for default mode (dynamic check) - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckKeyReadPermission() - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // only need to check for default mode (dynamic check) - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\.").Demand(); - } - } - - private bool ContainsRegistryValue(string name) - { - int type = 0; - int datasize = 0; - int retval = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - return retval == 0; - } - - private void EnsureNotDisposed() - { - if (_hkey == null) - { - throw new ObjectDisposedException(_keyName, - RegistryProviderStrings.ObjectDisposed_RegKeyClosed); - } - } - - private void EnsureWriteable() - { - EnsureNotDisposed(); - if (!IsWritable()) - { - throw new UnauthorizedAccessException(RegistryProviderStrings.UnauthorizedAccess_RegistryNoWrite); - } - } - - private static int GetRegistryKeyAccess(bool isWritable) - { - int winAccess; - if (!isWritable) - { - winAccess = Win32Native.KEY_READ; - } - else - { - winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; - } - - return winAccess; - } - - private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) - { - int winAccess = 0; - switch (mode) - { - case RegistryKeyPermissionCheck.ReadSubTree: - case RegistryKeyPermissionCheck.Default: - winAccess = Win32Native.KEY_READ; - break; - - case RegistryKeyPermissionCheck.ReadWriteSubTree: - winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; - break; - - default: - BCLDebug.Assert(false, "unexpected code path"); - break; - } - - return winAccess; - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - return _checkMode; - } - - if (subkeyWritable) - { - return RegistryKeyPermissionCheck.ReadWriteSubTree; - } - else - { - return RegistryKeyPermissionCheck.ReadSubTree; - } - } - - private static void ValidateKeyName(string name) - { - ArgumentNullException.ThrowIfNull(name, RegistryProviderStrings.Arg_Name); - - int nextSlash = name.IndexOf('\\'); - int current = 0; - while (nextSlash != -1) - { - if ((nextSlash - current) > MaxKeyLength) - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - - current = nextSlash + 1; - nextSlash = name.IndexOf('\\', current); - } - - if ((name.Length - current) > MaxKeyLength) - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - } - - private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) - { - if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) - { - throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck); - } - } - - private static void ValidateKeyRights(int rights) - { - if (0 != (rights & ~((int)RegistryRights.FullControl))) - { - // We need to throw SecurityException here for compatibility reason, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - } - - private void VerifyTransaction() - { - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - if (_myTransaction == null) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NotAssociatedWithTransaction); - } - - if (!_myTransaction.Equals(Transaction.Current)) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); - } - } - // Win32 constants for error handling - private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; - } -} diff --git a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs deleted file mode 100644 index 8bcf8d76880..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ /dev/null @@ -1,456 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\System\Security\AccessControl\RegistrySecurity.cs. -// Namespace: System.Security.AccessControl -// -/*============================================================ -** -** -** -** Purpose: Managed ACL wrapper for registry keys. -** -** -===========================================================*/ - -using System; -using System.Security.Permissions; -using System.Security.Principal; -using System.Runtime.InteropServices; -using System.IO; -using System.Security.AccessControl; -using System.Diagnostics.CodeAnalysis; - -namespace Microsoft.PowerShell.Commands.Internal -{ - /// - /// Represents a set of access rights allowed or denied for a user or group. This class cannot be inherited. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryAccessRule : AccessRule - { - // Constructor for creating access rules for registry objects - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) - : this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// - /// The name of the user or group the rule applies to. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type) - : this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. - /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - public TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// - /// The name of the user or group the rule applies to. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. - /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type) - { - } - - // - // Internal constructor to be called by public constructors - // and the access rule factory methods of {File|Folder}Security - // - internal TransactedRegistryAccessRule( - IdentityReference identity, - int accessMask, - bool isInherited, - InheritanceFlags inheritanceFlags, - PropagationFlags propagationFlags, - AccessControlType type) - : base( - identity, - accessMask, - isInherited, - inheritanceFlags, - propagationFlags, - type) - { - } - - /// - /// Gets the rights allowed or denied by the access rule. - /// - public RegistryRights RegistryRights - { - get { return (RegistryRights)base.AccessMask; } - } - } - - /// - /// Represents a set of access rights to be audited for a user or group. This class cannot be inherited. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryAuditRule : AuditRule - { - /// - /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to - /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. - /// - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. - /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. - /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. - /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - internal TransactedRegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags) - { - } - - /// - /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to - /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. - /// - /// The name of the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. - /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. - /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. - /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - internal TransactedRegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags) - { - } - - internal TransactedRegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) - { - } - - /// - /// Gets the access rights affected by the audit rule. - /// - public RegistryRights RegistryRights - { - get { return (RegistryRights)base.AccessMask; } - } - } - - /// - /// Represents the Windows access control security for a registry key. This class cannot be inherited. - /// This class is specifically to be used with TransactedRegistryKey. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistrySecurity : NativeObjectSecurity - { - private const string resBaseName = "RegistryProviderStrings"; - - /// - /// Initializes a new instance of the TransactedRegistrySecurity class with default values. - /// - public TransactedRegistrySecurity() - : base(true, ResourceType.RegistryKey) - { - } - - /* - // The name of registry key must start with a predefined string, - // like CLASSES_ROOT, CURRENT_USER, MACHINE, and USERS. See - // MSDN's help for SetNamedSecurityInfo for details. - internal TransactedRegistrySecurity(string name, AccessControlSections includeSections) - : base(true, ResourceType.RegistryKey, HKeyNameToWindowsName(name), includeSections) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); - } - */ - - // Suppressed because the passed name and hkey won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - internal TransactedRegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections) - : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); - } - - private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) - { - System.Exception exception = null; - - switch (errorCode) - { - case Win32Native.ERROR_FILE_NOT_FOUND: - exception = new IOException(RegistryProviderStrings.Arg_RegKeyNotFound); - break; - - case Win32Native.ERROR_INVALID_NAME: - exception = new ArgumentException(RegistryProviderStrings.Arg_RegInvalidKeyName); - break; - - case Win32Native.ERROR_INVALID_HANDLE: - exception = new ArgumentException(RegistryProviderStrings.AccessControl_InvalidHandle); - break; - - default: - break; - } - - return exception; - } - - /// - /// Creates a new access control rule for the specified user, with the specified access rights, access control, and flags. - /// - /// A TransactedRegistryAccessRule object representing the specified rights for the specified user. - /// An IdentityReference that identifies the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the access rights to allow or deny, cast to an integer. - /// A Boolean value specifying whether the rule is inherited. - /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. - /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. - /// One of the AccessControlType values specifying whether the rights are allowed or denied. - public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - { - return new TransactedRegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); - } - - /// - /// Creates a new audit rule, specifying the user the rule applies to, the access rights to audit, the inheritance and propagation of the - /// rule, and the outcome that triggers the rule. - /// - /// A TransactedRegistryAuditRule object representing the specified audit rule for the specified user, with the specified flags. - /// The return type of the method is the base class, AuditRule, but the return value can be cast safely to the derived class. - /// An IdentityReference that identifies the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the access rights to audit, cast to an integer. - /// A Boolean value specifying whether the rule is inherited. - /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. - /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. - /// A bitwise combination of AuditFlags values specifying whether to audit successful access, failed access, or both. - public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - { - return new TransactedRegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); - } - - internal AccessControlSections GetAccessControlSectionsFromChanges() - { - AccessControlSections persistRules = AccessControlSections.None; - if (AccessRulesModified) - persistRules = AccessControlSections.Access; - if (AuditRulesModified) - persistRules |= AccessControlSections.Audit; - if (OwnerModified) - persistRules |= AccessControlSections.Owner; - if (GroupModified) - persistRules |= AccessControlSections.Group; - return persistRules; - } - - // Suppressed because the passed keyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - internal void Persist(SafeRegistryHandle hKey, string keyName) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand(); - - WriteLock(); - - try - { - AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); - if (persistRules == AccessControlSections.None) - return; // Don't need to persist anything. - - base.Persist(hKey, persistRules); - OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; - } - finally - { - WriteUnlock(); - } - } - - /// - /// Searches for a matching access control with which the new rule can be merged. If none are found, adds the new rule. - /// - /// The access control rule to add. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void AddAccessRule(TransactedRegistryAccessRule rule) - { - base.AddAccessRule(rule); - } - - /// - /// Removes all access control rules with the same user and AccessControlType (allow or deny) as the specified rule, and then adds the specified rule. - /// - /// The TransactedRegistryAccessRule to add. The user and AccessControlType of this rule determine the rules to remove before this rule is added. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void SetAccessRule(TransactedRegistryAccessRule rule) - { - base.SetAccessRule(rule); - } - - /// - /// Removes all access control rules with the same user as the specified rule, regardless of AccessControlType, and then adds the specified rule. - /// - /// The TransactedRegistryAccessRule to add. The user specified by this rule determines the rules to remove before this rule is added. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void ResetAccessRule(TransactedRegistryAccessRule rule) - { - base.ResetAccessRule(rule); - } - - /// - /// Searches for an access control rule with the same user and AccessControlType (allow or deny) as the specified access rule, and with compatible - /// inheritance and propagation flags; if such a rule is found, the rights contained in the specified access rule are removed from it. - /// - /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for, and a set of inheritance - /// and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public bool RemoveAccessRule(TransactedRegistryAccessRule rule) - { - return base.RemoveAccessRule(rule); - } - - /// - /// Searches for all access control rules with the same user and AccessControlType (allow or deny) as the specified rule and, if found, removes them. - /// - /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for. Any rights, inheritance flags, or - /// propagation flags specified by this rule are ignored. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAccessRuleAll(TransactedRegistryAccessRule rule) - { - base.RemoveAccessRuleAll(rule); - } - - /// - /// Searches for an access control rule that exactly matches the specified rule and, if found, removes it. - /// - /// The TransactedRegistryAccessRule to remove. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAccessRuleSpecific(TransactedRegistryAccessRule rule) - { - base.RemoveAccessRuleSpecific(rule); - } - - /// - /// Searches for an audit rule with which the new rule can be merged. If none are found, adds the new rule. - /// - /// The audit rule to add. The user specified by this rule determines the search. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void AddAuditRule(TransactedRegistryAuditRule rule) - { - base.AddAuditRule(rule); - } - - /// - /// Removes all audit rules with the same user as the specified rule, regardless of the AuditFlags value, and then adds the specified rule. - /// - /// The TransactedRegistryAuditRule to add. The user specified by this rule determines the rules to remove before this rule is added. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void SetAuditRule(TransactedRegistryAuditRule rule) - { - base.SetAuditRule(rule); - } - - /// - /// Searches for an audit control rule with the same user as the specified rule, and with compatible inheritance and propagation flags; - /// if a compatible rule is found, the rights contained in the specified rule are removed from it. - /// - /// A TransactedRegistryAuditRule that specifies the user to search for, and a set of inheritance and propagation flags that - /// a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public bool RemoveAuditRule(TransactedRegistryAuditRule rule) - { - return base.RemoveAuditRule(rule); - } - - /// - /// Searches for all audit rules with the same user as the specified rule and, if found, removes them. - /// - /// A TransactedRegistryAuditRule that specifies the user to search for. Any rights, inheritance - /// flags, or propagation flags specified by this rule are ignored. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAuditRuleAll(TransactedRegistryAuditRule rule) - { - base.RemoveAuditRuleAll(rule); - } - - /// - /// Searches for an audit rule that exactly matches the specified rule and, if found, removes it. - /// - /// The TransactedRegistryAuditRule to be removed. - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAuditRuleSpecific(TransactedRegistryAuditRule rule) - { - base.RemoveAuditRuleSpecific(rule); - } - - /// - /// Gets the enumeration type that the TransactedRegistrySecurity class uses to represent access rights. - /// - /// A Type object representing the RegistryRights enumeration. - public override Type AccessRightType - { - get { return typeof(RegistryRights); } - } - - /// - /// Gets the type that the TransactedRegistrySecurity class uses to represent access rules. - /// - /// A Type object representing the TransactedRegistryAccessRule class. - public override Type AccessRuleType - { - get { return typeof(TransactedRegistryAccessRule); } - } - - /// - /// Gets the type that the TransactedRegistrySecurity class uses to represent audit rules. - /// - /// A Type object representing the TransactedRegistryAuditRule class. - public override Type AuditRuleType - { - get { return typeof(TransactedRegistryAuditRule); } - } - } -} diff --git a/src/System.Management.Automation/resources/CoreMshSnapinResources.resx b/src/System.Management.Automation/resources/CoreMshSnapinResources.resx deleted file mode 100644 index 39cb1e1b628..00000000000 --- a/src/System.Management.Automation/resources/CoreMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - This PowerShell snap-in contains cmdlets used to manage components of PowerShell. - - - Microsoft Corporation - - - Core PowerShell snap-in - - diff --git a/src/System.Management.Automation/resources/ErrorPackageRemoting.resx b/src/System.Management.Automation/resources/ErrorPackageRemoting.resx deleted file mode 100644 index add4b52ccf4..00000000000 --- a/src/System.Management.Automation/resources/ErrorPackageRemoting.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs deleted file mode 100644 index ac74a32d352..00000000000 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - using System; - using System.Diagnostics.Eventing; - using System.Management.Automation.Tracing; - using System.Threading; - - /// - /// An object that can be used to execute a method on a threadpool thread while correctly - /// managing system state, such as flowing ETW activities from the current thread to the - /// threadpool thread. - /// - public interface IBackgroundDispatcher - { - /// - /// Works the same as , except that it - /// also manages system state correctly. - /// - bool QueueUserWorkItem(WaitCallback callback); - - /// - /// Works the same as , except that it - /// also manages system state correctly. - /// - bool QueueUserWorkItem(WaitCallback callback, object state); - - /// - /// Works the same as BeginInvoke would for any other delegate, except that it also manages system state correctly. - /// - IAsyncResult BeginInvoke(WaitCallback callback, object state, AsyncCallback completionCallback, object asyncState); - - /// - /// Works the same as EndInvoke would for any other delegate, except that it also manages system state correctly. - /// - void EndInvoke(IAsyncResult asyncResult); - } - - /// - /// A simple implementation of . - /// - public class BackgroundDispatcher : - IBackgroundDispatcher - { - #region Instance Data - - private readonly IMethodInvoker _etwActivityMethodInvoker; - private readonly WaitCallback _invokerWaitCallback; - - #endregion - - #region Creation/Cleanup - - /// - /// Creates a that uses an - /// for activity creation and correlation. - /// - /// The to use when logging transfer events - /// during activity correlation. - /// The to use when logging transfer events - /// during activity correlation. - public BackgroundDispatcher(EventProvider transferProvider, EventDescriptor transferEvent) - : this(new EtwActivityReverterMethodInvoker(new EtwEventCorrelator(transferProvider, transferEvent))) - { - // nothing - } - - // internal for unit testing only. Otherwise, would be private. - internal BackgroundDispatcher(IMethodInvoker etwActivityMethodInvoker) - { - ArgumentNullException.ThrowIfNull(etwActivityMethodInvoker); - _etwActivityMethodInvoker = etwActivityMethodInvoker; - _invokerWaitCallback = DoInvoker; - } - - #endregion - - #region Instance Utilities - - private void DoInvoker(object invokerArgs) - { - var invokerArgsArray = (object[])invokerArgs; - - _etwActivityMethodInvoker.Invoker.DynamicInvoke(invokerArgsArray); - } - - #endregion - - #region Instance Access - - /// - /// Implements . - /// - public bool QueueUserWorkItem(WaitCallback callback) - { - return QueueUserWorkItem(callback, null); - } - - /// - /// Implements . - /// - public bool QueueUserWorkItem(WaitCallback callback, object state) - { - var invokerArgs = _etwActivityMethodInvoker.CreateInvokerArgs(callback, new object[] { state }); - - var result = ThreadPool.QueueUserWorkItem(_invokerWaitCallback, invokerArgs); - return result; - } - - /// - /// Implements . - /// - public IAsyncResult BeginInvoke(WaitCallback callback, object state, AsyncCallback completionCallback, object asyncState) - { - var invokerArgs = _etwActivityMethodInvoker.CreateInvokerArgs(callback, new object[] { state }); - - var result = _invokerWaitCallback.BeginInvoke(invokerArgs, completionCallback, asyncState); - return result; - } - - /// - /// Implements . - /// - public void EndInvoke(IAsyncResult asyncResult) - { - _invokerWaitCallback.EndInvoke(asyncResult); - } - - #endregion - } -} diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs deleted file mode 100644 index 995b41fcda1..00000000000 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ /dev/null @@ -1,596 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.PerformanceData; -using System.Globalization; -using System.Management.Automation.Tracing; - -namespace System.Management.Automation.PerformanceData -{ - /// - /// An abstract class that forms the base class for any Counter Set type. - /// A Counter Set Instance is required to register a given performance counter category - /// with PSPerfCountersMgr. - /// - public abstract class CounterSetInstanceBase : IDisposable - { - private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - #region Protected Members - - /// - /// An instance of counterSetRegistrarBase type encapsulates all the information - /// about a counter set and its associated counters. - /// - [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - protected CounterSetRegistrarBase _counterSetRegistrarBase; - - // NOTE: Check whether the following dictionaries need to be concurrent - // because there would be only 1 thread creating the instance, - // and that instance would then be shared by multiple threads for data access. - // Those threads won't modify/manipulate the dictionary, but they would only access it. - - /// - /// Dictionary mapping counter name to id. - /// - [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - protected ConcurrentDictionary _counterNameToIdMapping; - /// - /// Dictionary mapping counter id to counter type. - /// - [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - protected ConcurrentDictionary _counterIdToTypeMapping; - - #region Constructors - /// - /// Constructor. - /// - protected CounterSetInstanceBase(CounterSetRegistrarBase counterSetRegistrarInst) - { - this._counterSetRegistrarBase = counterSetRegistrarInst; - _counterNameToIdMapping = new ConcurrentDictionary(); - _counterIdToTypeMapping = new ConcurrentDictionary(); - - CounterInfo[] counterInfoArray = this._counterSetRegistrarBase.CounterInfoArray; - - for (int i = 0; i < counterInfoArray.Length; i++) - { - this._counterIdToTypeMapping.TryAdd(counterInfoArray[i].Id, counterInfoArray[i].Type); - if (!string.IsNullOrWhiteSpace(counterInfoArray[i].Name)) - { - this._counterNameToIdMapping.TryAdd(counterInfoArray[i].Name, counterInfoArray[i].Id); - } - } - } - - #endregion - - /// - /// Method that retrieves the target counter id. - /// NOTE: If isNumerator is true, then input counter id is returned. - /// But, if isNumerator is false, then a check is made on the input - /// counter's type to ensure that denominator is indeed value for such a counter. - /// - protected bool RetrieveTargetCounterIdIfValid(int counterId, bool isNumerator, out int targetCounterId) - { - targetCounterId = counterId; - if (isNumerator == false) - { - bool isDenominatorValid = false; - CounterType counterType = this._counterIdToTypeMapping[counterId]; - switch (counterType) - { - case CounterType.MultiTimerPercentageActive: - case CounterType.MultiTimerPercentageActive100Ns: - case CounterType.MultiTimerPercentageNotActive: - case CounterType.MultiTimerPercentageNotActive100Ns: - case CounterType.RawFraction32: - case CounterType.RawFraction64: - case CounterType.SampleFraction: - case CounterType.AverageCount64: - case CounterType.AverageTimer32: - isDenominatorValid = true; - break; - } - - if (isDenominatorValid == false) - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Denominator for update not valid for the given counter id {0}", - counterId)); - _tracer.TraceException(invalidOperationException); - return false; - } - - targetCounterId = counterId + 1; - } - - return true; - } - - #endregion - - #region Public Methods - - /// - /// If isNumerator is true, then updates the numerator component - /// of target counter 'counterId' by a value given by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public abstract bool UpdateCounterByValue( - int counterId, - long stepAmount, - bool isNumerator); - - /// - /// If isNumerator is true, then updates the numerator component - /// of target counter 'counterName' by a value given by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public abstract bool UpdateCounterByValue( - string counterName, - long stepAmount, - bool isNumerator); - - /// - /// If isNumerator is true, then sets the numerator component of target - /// counter 'counterId' to 'counterValue'. - /// Otherwise, sets the denominator component to 'counterValue'. - /// - public abstract bool SetCounterValue( - int counterId, - long counterValue, - bool isNumerator); - - /// - /// If isNumerator is true, then sets the numerator component of target - /// Counter 'counterName' to 'counterValue'. - /// Otherwise, sets the denominator component to 'counterValue'. - /// - public abstract bool SetCounterValue( - string counterName, - long counterValue, - bool isNumerator); - - /// - /// This method retrieves the counter value associated with counter 'counterId' - /// based on isNumerator parameter. - /// - public abstract bool GetCounterValue(int counterId, bool isNumerator, out long counterValue); - - /// - /// This method retrieves the counter value associated with counter 'counterName' - /// based on isNumerator parameter. - /// - public abstract bool GetCounterValue(string counterName, bool isNumerator, out long counterValue); - - /// - /// An abstract method that will be implemented by the derived type - /// so as to dispose the appropriate counter set instance. - /// - public abstract void Dispose(); - - /* - /// - /// Resets the target counter 'counterId' to 0. If the given - /// counter has both numerator and denominator components, then - /// they both are set to 0. - /// - public bool ResetCounter( - int counterId) - { - this.SetCounterValue(counterId, 0, true); - this.SetCounterValue(counterId, 0, false); - } - - /// - /// Resets the target counter 'counterName' to 0. If the given - /// counter has both numerator and denominator components, then - /// they both are set to 0. - /// - public void ResetCounter(string counterName) - { - this.SetCounterValue(counterName, 0, true); - this.SetCounterValue(counterName, 0, false); - } - */ - #endregion - } - - /// - /// PSCounterSetInstance is a thin wrapper - /// on System.Diagnostics.PerformanceData.CounterSetInstance. - /// - public class PSCounterSetInstance : CounterSetInstanceBase - { - #region Private Members - private bool _Disposed; - private CounterSet _CounterSet; - private CounterSetInstance _CounterSetInstance; - private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - - #region Private Methods - - private void CreateCounterSetInstance() - { - _CounterSet = - new CounterSet( - base._counterSetRegistrarBase.ProviderId, - base._counterSetRegistrarBase.CounterSetId, - base._counterSetRegistrarBase.CounterSetInstType); - - // Add the counters to the counter set definition. - foreach (CounterInfo counterInfo in base._counterSetRegistrarBase.CounterInfoArray) - { - if (counterInfo.Name == null) - { - _CounterSet.AddCounter(counterInfo.Id, counterInfo.Type); - } - else - { - _CounterSet.AddCounter(counterInfo.Id, counterInfo.Type, counterInfo.Name); - } - } - - string instanceName = PSPerfCountersMgr.Instance.GetCounterSetInstanceName(); - // Create an instance of the counter set (contains the counter data). - _CounterSetInstance = _CounterSet.CreateCounterSetInstance(instanceName); - } - - private void UpdateCounterByValue(CounterData TargetCounterData, long stepAmount) - { - Debug.Assert(TargetCounterData != null); - if (stepAmount == -1) - { - TargetCounterData.Decrement(); - } - else if (stepAmount == 1) - { - TargetCounterData.Increment(); - } - else - { - TargetCounterData.IncrementBy(stepAmount); - } - } - - #endregion - - #endregion - - #region Constructors - /// - /// Constructor for creating an instance of PSCounterSetInstance. - /// - public PSCounterSetInstance(CounterSetRegistrarBase counterSetRegBaseObj) - : base(counterSetRegBaseObj) - { - CreateCounterSetInstance(); - } - - #endregion - - #region Destructor - - /// - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives the base class opportunity to finalize. - /// - ~PSCounterSetInstance() - { - Dispose(false); - } - - #endregion - - #region Protected Methods - /// - /// Dispose(bool disposing) executes in two distinct scenarios. - /// If disposing equals true, the method has been called directly - /// or indirectly by a user's code. Managed and unmanaged resources - /// can be disposed. - /// If disposing equals false, the method has been called by the - /// runtime from inside the finalizer and you should not reference - /// other objects. Only unmanaged resources can be disposed. - /// - protected virtual void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!_Disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - _CounterSetInstance.Dispose(); - _CounterSet.Dispose(); - } - // Note disposing has been done. - _Disposed = true; - } - } - - #endregion - - #region IDisposable Overrides - /// - /// Dispose Method implementation for IDisposable interface. - /// - public override void Dispose() - { - this.Dispose(true); - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - #endregion - - #region CounterSetInstanceBase Overrides - - #region Public Methods - - /// - /// If isNumerator is true, then updates the numerator component - /// of target counter 'counterId' by a value given by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public override bool UpdateCounterByValue(int counterId, long stepAmount, bool isNumerator) - { - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - - int targetCounterId; - if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) - { - CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - if (targetCounterData != null) - { - this.UpdateCounterByValue(targetCounterData, stepAmount); - return true; - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter id {0} failed", - counterId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - else - { - return false; - } - } - /// - /// If isNumerator is true, then updates the numerator component - /// of target counter 'counterName' by a value given by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public override bool UpdateCounterByValue(string counterName, long stepAmount, bool isNumerator) - { - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - // retrieve counter id associated with the counter name - if (counterName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName)); - _tracer.TraceException(argNullException); - return false; - } - - try - { - int targetCounterId = this._counterNameToIdMapping[counterName]; - return this.UpdateCounterByValue(targetCounterId, stepAmount, isNumerator); - } - catch (KeyNotFoundException) - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter name {0} failed", - counterName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If isNumerator is true, then sets the numerator component - /// of target counter 'counterId' to 'counterValue'. - /// Otherwise, sets the denominator component to 'counterValue'. - /// - public override bool SetCounterValue(int counterId, long counterValue, bool isNumerator) - { - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - - int targetCounterId; - if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) - { - CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - - if (targetCounterData != null) - { - targetCounterData.Value = counterValue; - return true; - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter id {0} failed", - counterId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - else - { - return false; - } - } - - /// - /// If isNumerator is true, then updates the numerator component - /// of target counter 'counterName' by a value given by 'counterValue'. - /// Otherwise, sets the denominator component to 'counterValue'. - /// - public override bool SetCounterValue(string counterName, long counterValue, bool isNumerator) - { - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - - // retrieve counter id associated with the counter name - if (counterName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName)); - _tracer.TraceException(argNullException); - return false; - } - - try - { - int targetCounterId = this._counterNameToIdMapping[counterName]; - return this.SetCounterValue(targetCounterId, counterValue, isNumerator); - } - catch (KeyNotFoundException) - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter name {0} failed", - counterName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// This method retrieves the counter value associated with counter 'counterId' - /// based on isNumerator parameter. - /// - public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue) - { - counterValue = -1; - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - - int targetCounterId; - if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) - { - CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - - if (targetCounterData != null) - { - counterValue = targetCounterData.Value; - return true; - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter id {0} failed", - counterId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - else - { - return false; - } - } - - /// - /// This method retrieves the counter value associated with counter 'counterName' - /// based on isNumerator parameter. - /// - public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue) - { - counterValue = -1; - if (_Disposed) - { - ObjectDisposedException objectDisposedException = - new ObjectDisposedException("PSCounterSetInstance"); - _tracer.TraceException(objectDisposedException); - return false; - } - - // retrieve counter id associated with the counter name - if (counterName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterName)); - _tracer.TraceException(argNullException); - return false; - } - - try - { - int targetCounterId = this._counterNameToIdMapping[counterName]; - return this.GetCounterValue(targetCounterId, isNumerator, out counterValue); - } - catch (KeyNotFoundException) - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter name {0} failed", - counterName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - #endregion - #endregion - } -} diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs deleted file mode 100644 index 1ea57a16912..00000000000 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.PerformanceData; - -namespace System.Management.Automation.PerformanceData -{ - /// - /// A struct that encapsulates the information pertaining to a given counter - /// like name,type and id. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - public struct CounterInfo - { - #region Private Members - - #endregion - - #region Constructors - /// - /// Constructor. - /// - public CounterInfo(int id, CounterType type, string name) - { - Id = id; - Type = type; - Name = name; - } - - /// - /// Constructor. - /// - public CounterInfo(int id, CounterType type) - { - Id = id; - Type = type; - Name = null; - } - #endregion - - #region Properties - /// - /// Getter for Counter Name property. - /// - public string Name { get; } - - /// - /// Getter for Counter Id property. - /// - public int Id { get; } - - /// - /// Getter for Counter Type property. - /// - [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] - public CounterType Type { get; } - - #endregion - } - - /// - /// An abstract class that forms the base class for any CounterSetRegistrar type. - /// Any client that needs to register a new type of perf counter category with the - /// PSPerfCountersMgr, should create an instance of CounterSetRegistrarBase's - /// derived non-abstract type. - /// The created instance is then passed to PSPerfCounterMgr's AddCounterSetInstance() - /// method. - /// - public abstract class CounterSetRegistrarBase - { - #region Private Members - - #endregion - - #region Protected Members - /// - /// A reference to the encapsulated counter set instance. - /// - [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - protected CounterSetInstanceBase _counterSetInstanceBase; - - /// - /// Method that creates an instance of the CounterSetInstanceBase's derived type. - /// This method is invoked by the PSPerfCountersMgr to retrieve the appropriate - /// instance of CounterSet to register with its internal datastructure. - /// - protected abstract CounterSetInstanceBase CreateCounterSetInstance(); - - #endregion - - #region Constructors - /// - /// Constructor that creates an instance of CounterSetRegistrarBase derived type - /// based on Provider Id, counterSetId, counterSetInstanceType, a collection - /// with counters information and an optional counterSetName. - /// - protected CounterSetRegistrarBase( - Guid providerId, - Guid counterSetId, - CounterSetInstanceType counterSetInstType, - CounterInfo[] counterInfoArray, - string counterSetName = null) - { - ProviderId = providerId; - CounterSetId = counterSetId; - CounterSetInstType = counterSetInstType; - CounterSetName = counterSetName; - - if (counterInfoArray is null || counterInfoArray.Length == 0) - { - throw new ArgumentNullException(nameof(counterInfoArray)); - } - - CounterInfoArray = new CounterInfo[counterInfoArray.Length]; - - for (int i = 0; i < counterInfoArray.Length; i++) - { - CounterInfoArray[i] = - new CounterInfo( - counterInfoArray[i].Id, - counterInfoArray[i].Type, - counterInfoArray[i].Name - ); - } - - this._counterSetInstanceBase = null; - } - - /// - /// Copy constructor. - /// - protected CounterSetRegistrarBase( - CounterSetRegistrarBase srcCounterSetRegistrarBase) - { - ArgumentNullException.ThrowIfNull(srcCounterSetRegistrarBase); - - ProviderId = srcCounterSetRegistrarBase.ProviderId; - CounterSetId = srcCounterSetRegistrarBase.CounterSetId; - CounterSetInstType = srcCounterSetRegistrarBase.CounterSetInstType; - CounterSetName = srcCounterSetRegistrarBase.CounterSetName; - - CounterInfo[] counterInfoArrayRef = srcCounterSetRegistrarBase.CounterInfoArray; - CounterInfoArray = new CounterInfo[counterInfoArrayRef.Length]; - - for (int i = 0; i < counterInfoArrayRef.Length; i++) - { - CounterInfoArray[i] = - new CounterInfo( - counterInfoArrayRef[i].Id, - counterInfoArrayRef[i].Type, - counterInfoArrayRef[i].Name); - } - } - #endregion - - #region Properties - - /// - /// Getter method for ProviderId property. - /// - public Guid ProviderId { get; } - - /// - /// Getter method for CounterSetId property. - /// - public Guid CounterSetId { get; } - - /// - /// Getter method for CounterSetName property. - /// - public string CounterSetName { get; } - - /// - /// Getter method for CounterSetInstanceType property. - /// - public CounterSetInstanceType CounterSetInstType { get; } - - /// - /// Getter method for array of counters information property. - /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public CounterInfo[] CounterInfoArray { get; } - - /// - /// Getter method that returns an instance of the CounterSetInstanceBase's - /// derived type. - /// - public CounterSetInstanceBase CounterSetInstance - { - get { return _counterSetInstanceBase ?? (_counterSetInstanceBase = CreateCounterSetInstance()); } - } - - #endregion - - #region Public Methods - - /// - /// Method that disposes the referenced instance of the CounterSetInstanceBase's derived type. - /// This method is invoked by the PSPerfCountersMgr to dispose the appropriate - /// instance of CounterSet from its internal datastructure as part of PSPerfCountersMgr - /// cleanup procedure. - /// - public abstract void DisposeCounterSetInstance(); - - #endregion - } - - /// - /// PSCounterSetRegistrar implements the abstract methods of CounterSetRegistrarBase. - /// Any client that needs to register a new type of perf counter category with the - /// PSPerfCountersMgr, should create an instance of PSCounterSetRegistrar. - /// The created instance is then passed to PSPerfCounterMgr's AddCounterSetInstance() - /// method. - /// - public class PSCounterSetRegistrar : CounterSetRegistrarBase - { - #region Constructors - /// - /// Constructor that creates an instance of PSCounterSetRegistrar. - /// - public PSCounterSetRegistrar( - Guid providerId, - Guid counterSetId, - CounterSetInstanceType counterSetInstType, - CounterInfo[] counterInfoArray, - string counterSetName = null) - : base(providerId, counterSetId, counterSetInstType, counterInfoArray, counterSetName) - { - } - - /// - /// Copy Constructor. - /// - public PSCounterSetRegistrar( - PSCounterSetRegistrar srcPSCounterSetRegistrar) - : base(srcPSCounterSetRegistrar) - { - ArgumentNullException.ThrowIfNull(srcPSCounterSetRegistrar); - } - - #endregion - - #region CounterSetRegistrarBase Overrides - - #region Protected Methods - - /// - /// Method that creates an instance of the CounterSetInstanceBase's derived type. - /// - protected override CounterSetInstanceBase CreateCounterSetInstance() - { - return new PSCounterSetInstance(this); - } - - #endregion - - #region Public Methods - /// - /// Method that disposes the referenced instance of the CounterSetInstanceBase's derived type. - /// - public override void DisposeCounterSetInstance() - { - base._counterSetInstanceBase.Dispose(); - } - - #endregion - - #endregion - } -} diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs deleted file mode 100644 index 7a49a5c6f9f..00000000000 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Management.Automation.Tracing; - -namespace System.Management.Automation.PerformanceData -{ - /// - /// Powershell Performance Counters Manager class shall provide a mechanism - /// for components using SYstem.Management.Automation assembly to register - /// performance counters with Performance Counters subsystem. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public class PSPerfCountersMgr - { - #region Private Members - private static PSPerfCountersMgr s_PSPerfCountersMgrInstance; - private ConcurrentDictionary _CounterSetIdToInstanceMapping; - private ConcurrentDictionary _CounterSetNameToIdMapping; - private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - - #region Constructors - - private PSPerfCountersMgr() - { - _CounterSetIdToInstanceMapping = new ConcurrentDictionary(); - _CounterSetNameToIdMapping = new ConcurrentDictionary(); - } - - #endregion - - #endregion - - #region Destructor - - /// - /// Destructor which will trigger the cleanup of internal data structures and - /// disposal of counter set instances. - /// - ~PSPerfCountersMgr() - { - RemoveAllCounterSets(); - } - - #endregion - - #region Public Methods - - /// - /// Getter method to retrieve the singleton instance of the PSPerfCountersMgr. - /// - public static PSPerfCountersMgr Instance - { - get { return s_PSPerfCountersMgrInstance ?? (s_PSPerfCountersMgrInstance = new PSPerfCountersMgr()); } - } - - /// - /// Helper method to generate an instance name for a counter set. - /// - public string GetCounterSetInstanceName() - { - Process currentProcess = Process.GetCurrentProcess(); - string pid = string.Create(CultureInfo.InvariantCulture, $"{currentProcess.Id}"); - return pid; - } - - /// - /// Method to determine whether the counter set given by 'counterSetName' is - /// registered with the system. If true, then counterSetId is populated. - /// - public bool IsCounterSetRegistered(string counterSetName, out Guid counterSetId) - { - counterSetId = new Guid(); - if (counterSetName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); - _tracer.TraceException(argNullException); - return false; - } - - return _CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId); - } - - /// - /// Method to determine whether the counter set given by 'counterSetId' is - /// registered with the system. If true, then CounterSetInstance is populated. - /// - public bool IsCounterSetRegistered(Guid counterSetId, out CounterSetInstanceBase counterSetInst) - { - return _CounterSetIdToInstanceMapping.TryGetValue(counterSetId, out counterSetInst); - } - - /// - /// Method to register a counter set with the Performance Counters Manager. - /// - public bool AddCounterSetInstance(CounterSetRegistrarBase counterSetRegistrarInstance) - { - if (counterSetRegistrarInstance == null) - { - ArgumentNullException argNullException = new ArgumentNullException("counterSetRegistrarInstance"); - _tracer.TraceException(argNullException); - return false; - } - - Guid counterSetId = counterSetRegistrarInstance.CounterSetId; - string counterSetName = counterSetRegistrarInstance.CounterSetName; - CounterSetInstanceBase counterSetInst = null; - - if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) - { - InvalidOperationException invalidOperationException = new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "A Counter Set Instance with id '{0}' is already registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - return false; - } - - try - { - if (!string.IsNullOrWhiteSpace(counterSetName)) - { - Guid retrievedCounterSetId; - // verify that there doesn't exist another counter set with the same name - if (this.IsCounterSetRegistered(counterSetName, out retrievedCounterSetId)) - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "A Counter Set Instance with name '{0}' is already registered", - counterSetName)); - _tracer.TraceException(invalidOperationException); - return false; - } - - _CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId); - } - - _CounterSetIdToInstanceMapping.TryAdd( - counterSetId, - counterSetRegistrarInstance.CounterSetInstance); - } - catch (OverflowException overflowException) - { - _tracer.TraceException(overflowException); - return false; - } - - return true; - } - - /// - /// If IsNumerator is true, then updates the numerator component - /// of target counter 'counterId' in Counter Set 'counterSetId' - /// by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public bool UpdateCounterByValue( - Guid counterSetId, - int counterId, - long stepAmount = 1, - bool isNumerator = true) - { - CounterSetInstanceBase counterSetInst = null; - if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) - { - return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with id '{0}' is registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then updates the numerator component - /// of target counter 'counterName' in Counter Set 'counterSetId' - /// by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public bool UpdateCounterByValue( - Guid counterSetId, - string counterName, - long stepAmount = 1, - bool isNumerator = true) - { - CounterSetInstanceBase counterSetInst = null; - if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) - { - return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with id '{0}' is registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then updates the numerator component - /// of target counter 'counterId' in Counter Set 'counterSetName' - /// by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public bool UpdateCounterByValue( - string counterSetName, - int counterId, - long stepAmount = 1, - bool isNumerator = true) - { - if (counterSetName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); - _tracer.TraceException(argNullException); - return false; - } - - Guid counterSetId; - if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) - { - CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; - return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with id '{0}' is registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - - return false; - } - } - - /// - /// If IsNumerator is true, then updates the numerator component - /// of target counter 'counterName' in Counter Set 'counterSetName' - /// by 'stepAmount'. - /// Otherwise, updates the denominator component by 'stepAmount'. - /// - public bool UpdateCounterByValue( - string counterSetName, - string counterName, - long stepAmount = 1, - bool isNumerator = true) - { - Guid counterSetId; - if (counterSetName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); - _tracer.TraceException(argNullException); - return false; - } - - if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) - { - CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; - return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with name {0} is registered", - counterSetName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then sets the numerator component - /// of target counter 'counterId' in Counter Set 'counterSetId' - /// to 'counterValue'. - /// Otherwise, updates the denominator component to 'counterValue'. - /// - public bool SetCounterValue( - Guid counterSetId, - int counterId, - long counterValue = 1, - bool isNumerator = true) - { - CounterSetInstanceBase counterSetInst = null; - if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) - { - return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with id '{0}' is registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then sets the numerator component - /// of target counter 'counterName' in Counter Set 'counterSetId' - /// to 'counterValue'. - /// Otherwise, updates the denominator component to 'counterValue'. - /// - public bool SetCounterValue( - Guid counterSetId, - string counterName, - long counterValue = 1, - bool isNumerator = true) - { - CounterSetInstanceBase counterSetInst = null; - if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) - { - return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with id '{0}' is registered", - counterSetId)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then sets the numerator component - /// of target counter 'counterId' in Counter Set 'counterSetName' - /// to 'counterValue'. - /// Otherwise, updates the denominator component to 'counterValue'. - /// - public bool SetCounterValue( - string counterSetName, - int counterId, - long counterValue = 1, - bool isNumerator = true) - { - if (counterSetName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); - _tracer.TraceException(argNullException); - return false; - } - - Guid counterSetId; - if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) - { - CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; - return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with name '{0}' is registered", - counterSetName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - /// - /// If IsNumerator is true, then sets the numerator component - /// of target counter 'counterName' in Counter Set 'counterSetName' - /// to 'counterValue'. - /// Otherwise, updates the denominator component to 'counterValue'. - /// - public bool SetCounterValue( - string counterSetName, - string counterName, - long counterValue = 1, - bool isNumerator = true) - { - if (counterSetName == null) - { - ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); - _tracer.TraceException(argNullException); - return false; - } - - Guid counterSetId; - if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) - { - CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; - return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator); - } - else - { - InvalidOperationException invalidOperationException = - new InvalidOperationException( - string.Format( - CultureInfo.InvariantCulture, - "No Counter Set Instance with name '{0}' is registered", - counterSetName)); - _tracer.TraceException(invalidOperationException); - return false; - } - } - - #endregion - - #region Internal Methods - - /// - /// NOTE: This method is provided solely for testing purposes. - /// - internal void RemoveAllCounterSets() - { - ICollection counterSetIdKeys = _CounterSetIdToInstanceMapping.Keys; - foreach (Guid counterSetId in counterSetIdKeys) - { - CounterSetInstanceBase currentCounterSetInstance = _CounterSetIdToInstanceMapping[counterSetId]; - currentCounterSetInstance.Dispose(); - } - - _CounterSetIdToInstanceMapping.Clear(); - _CounterSetNameToIdMapping.Clear(); - } - - #endregion - } -} From 02d3fd1e831fcd2952f62f1ef76fe171bc5d4ce8 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 8 Jul 2026 10:14:46 -0700 Subject: [PATCH 2/2] Create 'LocProject.json' file and remove 'LocalAccounts' folder --- Localize/LocProject.json | 65 + .../Commands/AddLocalGroupMemberCommand.cs | 303 -- .../Commands/DisableLocalUserCommand.cs | 219 -- .../Commands/EnableLocalUserCommand.cs | 219 -- .../Commands/GetLocalGroupCommand.cs | 170 - .../Commands/GetLocalGroupMemberCommand.cs | 235 -- .../Commands/GetLocalUserCommand.cs | 172 - .../Commands/NewLocalGroupCommand.cs | 120 - .../Commands/NewLocalUserCommand.cs | 294 -- .../Commands/RemoveLocalGroupCommand.cs | 212 -- .../Commands/RemoveLocalGroupMemberCommand.cs | 301 -- .../Commands/RemoveLocalUserCommand.cs | 213 -- .../Commands/RenameLocalGroupCommand.cs | 232 -- .../Commands/RenameLocalUserCommand.cs | 232 -- .../Commands/SetLocalGroupCommand.cs | 179 - .../Commands/SetLocalUserCommand.cs | 322 -- .../LocalAccounts/Exceptions.cs | 689 ---- .../LocalAccounts/Extensions.cs | 206 -- .../LocalAccounts/LocalGroup.cs | 77 - .../LocalAccounts/LocalPrincipal.cs | 100 - .../LocalAccounts/LocalUser.cs | 142 - .../LocalAccounts/Native.cs | 424 --- .../LocalAccounts/NtStatus.cs | 519 --- .../LocalAccounts/PInvokeDllNames.cs | 30 - .../LocalAccounts/Sam.cs | 3275 ----------------- .../LocalAccounts/SamApi.cs | 468 --- .../LocalAccounts/StringUtil.cs | 70 - .../Microsoft.PowerShell.LocalAccounts.csproj | 14 - ...soft.PowerShell.LocalAccounts.Strings.resx | 234 -- 29 files changed, 65 insertions(+), 9671 deletions(-) create mode 100644 Localize/LocProject.json delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj delete mode 100644 src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx diff --git a/Localize/LocProject.json b/Localize/LocProject.json new file mode 100644 index 00000000000..0539b017f72 --- /dev/null +++ b/Localize/LocProject.json @@ -0,0 +1,65 @@ +{ + "Projects": [ + { + "LanguageSet": "VS_Main_Languages", + "LocItems": [ + { + "SourceFile": "src\\System.Management.Automation\\resources\\*.resx", + "OutputPath": "src\\System.Management.Automation\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.Management.Infrastructure.CimCmdlets\\resources\\*.resx", + "OutputPath": "src\\Microsoft.Management.Infrastructure.CimCmdlets\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\*.resx", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Diagnostics\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Diagnostics\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.CoreCLR.Eventing\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.CoreCLR.Eventing\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.LocalAccounts\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.LocalAccounts\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\*.resx", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + }, + { + "SourceFile": "src\\Microsoft.WSMan.Management\\resources\\*.resx", + "OutputPath": "src\\Microsoft.WSMan.Management\\resources\\{Lang}\\{FileName}.{Lang}{Extension}", + "CopyOption": "UsePlaceholders" + } + ] + } + ] +} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs deleted file mode 100644 index 59cb3067efc..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Management.Automation; -using System.Security.Principal; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Add-LocalGroupMember cmdlet adds one or more users or groups to a local - /// group. - /// - [Cmdlet(VerbsCommon.Add, "LocalGroupMember", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717987")] - [Alias("algm")] - public class AddLocalGroupMemberCommand : PSCmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Group". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "Group")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalGroup Group - { - get { return this.group;} - - set { this.group = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup group; - - /// - /// The following is the definition of the input parameter "Member". - /// Specifies one or more users or groups to add to this local group. You can - /// identify users or groups by specifying their names or SIDs, or by passing - /// Microsoft.PowerShell.Commands.LocalPrincipal objects. - /// - [Parameter(Mandatory = true, - Position = 1, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalPrincipal[] Member - { - get { return this.member;} - - set { this.member = value; } - } - - private Microsoft.PowerShell.Commands.LocalPrincipal[] member; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - if (Group != null) - ProcessGroup(Group); - else if (Name != null) - ProcessName(Name); - else if (SID != null) - ProcessSid(SID); - } - catch (GroupNotFoundException ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - - /// - /// Creates a list of objects - /// ready to be processed by the cmdlet. - /// - /// - /// Name or SID (as a string) of the group we'll be adding to. - /// This string is used primarily for specifying the target - /// in WhatIf scenarios. - /// - /// - /// LocalPrincipal object to be processed - /// - /// - /// A LocalPrincipal Object to be added to the group - /// - /// - /// - /// LocalPrincipal objects in the Member parameter may not be complete, - /// particularly those created from a name or a SID string given to the - /// Member cmdlet parameter. The object returned from this method contains - /// , at the very least, a valid SID. - /// - /// - /// Any Member objects provided by name or SID string will be looked up - /// to ensure that such an object exists. If an object is not found, - /// an error message is displayed by PowerShell and null will be returned - /// - /// - /// This method also handles the WhatIf scenario. If the Cmdlet's - /// ShouldProcess method returns false on any Member object, - /// that object will not be included in the returned List. - /// - /// - private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) - { - LocalPrincipal principal = null; - // if the member has a SID, we can use it directly - if (member.SID != null) - { - principal = member; - } - else // otherwise it must have been constructed by name - { - SecurityIdentifier sid = this.TrySid(member.Name); - - if (sid != null) - { - member.SID = sid; - principal = member; - } - else - { - try - { - principal = sam.LookupAccount(member.Name); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - if (CheckShouldProcess(principal, groupId)) - return principal; - - return null; - } - - /// - /// Determine if a principal should be processed. - /// Just a wrapper around Cmdlet.ShouldProcess, with localized string - /// formatting. - /// - /// Name of the principal to be added. - /// - /// Name of the group to which the members will be added. - /// - /// - /// True if the principal should be processed, false otherwise. - /// - private bool CheckShouldProcess(LocalPrincipal principal, string groupName) - { - if (principal == null) - return false; - - string msg = StringUtil.Format(Strings.ActionAddGroupMember, principal.ToString()); - - return ShouldProcess(groupName, msg); - } - - /// - /// Add members to a group. - /// - /// - /// A object representing the group to which - /// the members will be added. - /// - private void ProcessGroup(LocalGroup group) - { - string groupId = group.Name ?? group.SID.ToString(); - foreach (var member in this.Member) - { - LocalPrincipal principal = MakePrincipal(groupId, member); - if (principal != null) - { - var ex = sam.AddLocalGroupMember(group, principal); - if (ex != null) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Add members to a group specified by name. - /// - /// - /// The name of the group to which the members will be added. - /// - private void ProcessName(string name) - { - ProcessGroup(sam.GetLocalGroup(name)); - } - - /// - /// Add members to a group specified by SID. - /// - /// - /// A object identifying the group - /// to which the members will be added. - /// - private void ProcessSid(SecurityIdentifier groupSid) - { - foreach (var member in this.Member) - { - LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); - if (principal != null) - { - var ex = sam.AddLocalGroupMember(groupSid, principal); - if (ex != null) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs deleted file mode 100644 index 592c77726fe..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Disable-LocalUser cmdlet disables local user accounts. When a user - /// account is disabled, the user is not permitted to log on. When a user - /// account is enabled, the user is permitted to log on normally. - /// - [Cmdlet(VerbsLifecycle.Disable, "LocalUser", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717986")] - [Alias("dlu")] - public class DisableLocalUserCommand : Cmdlet - { - #region Constants - private const Enabling enabling = Enabling.Disable; - #endregion Constants - - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local user accounts to disable in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalUser[] InputObject - { - get { return this.inputobject; } - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalUser[] inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the names of the local user accounts to disable in the local - /// Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies the LocalUser accounts to disable by - /// System.Security.Principal.SecurityIdentifier. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessUsers(); - ProcessNames(); - ProcessSids(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process users requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var name in Name) - { - try - { - if (CheckShouldProcess(name)) - sam.EnableLocalUser(sam.GetLocalUser(name), enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var sid in SID) - { - try - { - if (CheckShouldProcess(sid.ToString())) - sam.EnableLocalUser(sid, enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -InputObject. - /// - private void ProcessUsers() - { - if (InputObject != null) - { - foreach (var user in InputObject) - { - try - { - if (CheckShouldProcess(user.Name)) - sam.EnableLocalUser(user, enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionDisableUser); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs deleted file mode 100644 index 88627ba2e33..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Enable-LocalUser cmdlet enables local user accounts. When a user account - /// is disabled, the user is not permitted to log on. When a user account is - /// enabled, the user is permitted to log on normally. - /// - [Cmdlet(VerbsLifecycle.Enable, "LocalUser", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717985")] - [Alias("elu")] - public class EnableLocalUserCommand : Cmdlet - { - #region Constants - private const Enabling enabling = Enabling.Enable; - #endregion Constants - - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local user accounts to enable in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalUser[] InputObject - { - get { return this.inputobject; } - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalUser[] inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local user accounts to enable in the local Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies the LocalUser accounts to enable by - /// System.Security.Principal.SecurityIdentifier. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessUsers(); - ProcessNames(); - ProcessSids(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process users requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var name in Name) - { - try - { - if (CheckShouldProcess(name)) - sam.EnableLocalUser(sam.GetLocalUser(name), enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var sid in SID) - { - try - { - if (CheckShouldProcess(sid.ToString())) - sam.EnableLocalUser(sid, enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -InputObject. - /// - private void ProcessUsers() - { - if (InputObject != null) - { - foreach (var user in InputObject) - { - try - { - if (CheckShouldProcess(user.Name)) - sam.EnableLocalUser(user, enabling); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionEnableUser); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs deleted file mode 100644 index 4c11a3c4c36..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; -using System.Security.Principal; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Get-LocalGroup cmdlet gets local groups from the Windows Security - /// Accounts manager. - /// - [Cmdlet(VerbsCommon.Get, "LocalGroup", - DefaultParameterSetName = "Default", - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717974")] - [Alias("glg")] - public class GetLocalGroupCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local groups to get from the local Security Accounts Manager. - /// - [Parameter(Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a local group from the local Security Accounts Manager. - /// - [Parameter(Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - if (Name == null && SID == null) - { - foreach (var group in sam.GetAllLocalGroups()) - WriteObject(group); - - return; - } - - ProcessNames(); - ProcessSids(); - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process groups requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// Groups may be specified using wildcards. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var name in Name) - { - try - { - if (WildcardPattern.ContainsWildcardCharacters(name)) - { - var pattern = new WildcardPattern(name, WildcardOptions.Compiled - | WildcardOptions.IgnoreCase); - - foreach (var group in sam.GetMatchingLocalGroups(n => pattern.IsMatch(n))) - WriteObject(group); - } - else - { - WriteObject(sam.GetLocalGroup(name)); - } - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process groups requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var sid in SID) - { - try - { - WriteObject(sam.GetLocalGroup(sid)); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs deleted file mode 100644 index 0b3625f6ef7..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Management.Automation; -using System.Security.Principal; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Get-LocalGroupMember cmdlet gets the members of a local group. - /// - [Cmdlet(VerbsCommon.Get, "LocalGroupMember", - DefaultParameterSetName = "Default", - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717988")] - [Alias("glgm")] - public class GetLocalGroupMemberCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Group". - /// The security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Group")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalGroup Group - { - get { return this.group;} - - set { this.group = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup group; - - /// - /// The following is the definition of the input parameter "Member". - /// Specifies the name of the user or group that is a member of this group. If - /// this parameter is not specified, all members of the specified group are - /// returned. This accepts a name, SID, or wildcard string. - /// - [Parameter(Position = 1)] - [ValidateNotNullOrEmpty] - public string Member - { - get { return this.member;} - - set { this.member = value; } - } - - private string member; - - /// - /// The following is the definition of the input parameter "Name". - /// The security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "SID". - /// The security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - IEnumerable principals = null; - - if (Group != null) - principals = ProcessGroup(Group); - else if (Name != null) - principals = ProcessName(Name); - else if (SID != null) - principals = ProcessSid(SID); - - if (principals != null) - WriteObject(principals, true); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - private IEnumerable ProcessesMembership(IEnumerable membership) - { - List rv; - - // if no members are specified, return all of them - if (Member == null) - { - // return membership; - rv = new List(membership); - } - else - { - // var rv = new List(); - rv = new List(); - - if (WildcardPattern.ContainsWildcardCharacters(Member)) - { - var pattern = new WildcardPattern(Member, WildcardOptions.Compiled - | WildcardOptions.IgnoreCase); - - foreach (var m in membership) - if (pattern.IsMatch(sam.StripMachineName(m.Name))) - rv.Add(m); - } - else - { - var sid = this.TrySid(Member); - - if (sid != null) - { - foreach (var m in membership) - { - if (m.SID == sid) - { - rv.Add(m); - break; - } - } - } - else - { - foreach (var m in membership) - { - if (sam.StripMachineName(m.Name).Equals(Member, StringComparison.CurrentCultureIgnoreCase)) - { - rv.Add(m); - break; - } - } - } - - if (rv.Count == 0) - { - var ex = new PrincipalNotFoundException(member, member); - WriteError(ex.MakeErrorRecord()); - } - } - } - - // sort the resulting principals by mane - rv.Sort(static (p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.CurrentCultureIgnoreCase)); - - return rv; - } - - private IEnumerable ProcessGroup(LocalGroup group) - { - return ProcessesMembership(sam.GetLocalGroupMembers(group)); - } - - private IEnumerable ProcessName(string name) - { - return ProcessGroup(sam.GetLocalGroup(name)); - } - - private IEnumerable ProcessSid(SecurityIdentifier groupSid) - { - return ProcessesMembership(sam.GetLocalGroupMembers(groupSid)); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs deleted file mode 100644 index 9f8d3b9311b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Get-LocalUser cmdlet gets local user accounts from the Windows Security - /// Accounts Manager. This includes local accounts that have been connected to a - /// Microsoft account. - /// - [Cmdlet(VerbsCommon.Get, "LocalUser", - DefaultParameterSetName = "Default", - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717980")] - [Alias("glu")] - public class GetLocalUserCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local user accounts to get from the local Security Accounts - /// Manager. This accepts a name or wildcard string. - /// - [Parameter(Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a user from the local Security Accounts Manager. - /// - [Parameter(Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid; } - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - if (Name == null && SID == null) - { - foreach (var user in sam.GetAllLocalUsers()) - WriteObject(user); - - return; - } - - ProcessNames(); - ProcessSids(); - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process users requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// Users may be specified using wildcards. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var nm in Name) - { - try - { - if (WildcardPattern.ContainsWildcardCharacters(nm)) - { - var pattern = new WildcardPattern(nm, WildcardOptions.Compiled - | WildcardOptions.IgnoreCase); - - foreach (var user in sam.GetMatchingLocalUsers(n => pattern.IsMatch(n))) - WriteObject(user); - } - else - { - WriteObject(sam.GetLocalUser(nm)); - } - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var s in SID) - { - try - { - WriteObject(sam.GetLocalUser(s)); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs deleted file mode 100644 index b709d22a485..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The New-LocalGroup Cmdlet can be used to create a new local security group - /// in the Windows Security Accounts Manager. - /// - [Cmdlet(VerbsCommon.New, "LocalGroup", - SupportsShouldProcess = true, - HelpUri ="https://go.microsoft.com/fwlink/?LinkId=717990")] - [Alias("nlg")] - public class NewLocalGroupCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Description". - /// A descriptive comment. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - [ValidateNotNull] - public string Description - { - get { return this.description;} - - set { this.description = value; } - } - - private string description; - - /// - /// The following is the definition of the input parameter "Name". - /// The group name for the local security group. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [ValidateLength(1, 256)] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - if (CheckShouldProcess(Name)) - { - var group = sam.CreateLocalGroup(new LocalGroup - { - Description = Description, - Name = Name - }); - - WriteObject(group); - } - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionNewGroup); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs deleted file mode 100644 index d3402b5a4c9..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The New-LocalUser cmdlet creates a new local user account. - /// - [Cmdlet(VerbsCommon.New, "LocalUser", - DefaultParameterSetName = "Password", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717981")] - [Alias("nlu")] - public class NewLocalUserCommand : PSCmdlet - { - #region Static Data - // Names of object- and boolean-type parameters. - // Switch parameters don't need to be included. - private static string[] parameterNames = new string[] - { - "AccountExpires", - "Description", - "Disabled", - "FullName", - "Password", - "UserMayNotChangePassword" - }; - #endregion Static Data - - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "AccountExpires". - /// Specifies when the user account will expire. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - public System.DateTime AccountExpires - { - get { return this.accountexpires;} - - set { this.accountexpires = value; } - } - - private System.DateTime accountexpires; - - // This parameter added by hand (copied from SetLocalUserCommand), not by Cmdlet Designer - /// - /// The following is the definition of the input parameter "AccountNeverExpires". - /// Specifies that the account will not expire. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - public System.Management.Automation.SwitchParameter AccountNeverExpires - { - get { return this.accountneverexpires;} - - set { this.accountneverexpires = value; } - } - - private System.Management.Automation.SwitchParameter accountneverexpires; - - /// - /// The following is the definition of the input parameter "Description". - /// A descriptive comment for this user account. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - [ValidateNotNull] - public string Description - { - get { return this.description;} - - set { this.description = value; } - } - - private string description; - - /// - /// The following is the definition of the input parameter "Disabled". - /// Specifies whether this user account is enabled or disabled. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - public System.Management.Automation.SwitchParameter Disabled - { - get { return this.disabled;} - - set { this.disabled = value; } - } - - private System.Management.Automation.SwitchParameter disabled; - - /// - /// The following is the definition of the input parameter "FullName". - /// Specifies the full name of the user account. This is different from the - /// username of the user account. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - [ValidateNotNull] - public string FullName - { - get { return this.fullname;} - - set { this.fullname = value; } - } - - private string fullname; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the user name for the local user account. This can be a local user - /// account or a local user account that is connected to a Microsoft Account. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [ValidateLength(1, 20)] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "Password". - /// Specifies the password for the local user account. A password can contain up - /// to 127 characters. - /// - [Parameter(Mandatory = true, - ParameterSetName = "Password", - ValueFromPipelineByPropertyName = true)] - [ValidateNotNull] - public System.Security.SecureString Password - { - get { return this.password;} - - set { this.password = value; } - } - - private System.Security.SecureString password; - - /// - /// The following is the definition of the input parameter "PasswordChangeableDate". - /// Specifies that the new User account has no password. - /// - [Parameter(Mandatory = true, - ParameterSetName = "NoPassword", - ValueFromPipelineByPropertyName = true)] - public System.Management.Automation.SwitchParameter NoPassword - { - get { return this.nopassword; } - - set { this.nopassword = value; } - } - - private System.Management.Automation.SwitchParameter nopassword; - - /// - /// The following is the definition of the input parameter "PasswordNeverExpires". - /// Specifies that the password will not expire. - /// - [Parameter(ParameterSetName = "Password", - ValueFromPipelineByPropertyName = true)] - public System.Management.Automation.SwitchParameter PasswordNeverExpires - { - get { return this.passwordneverexpires; } - - set { this.passwordneverexpires = value; } - } - - private System.Management.Automation.SwitchParameter passwordneverexpires; - - /// - /// The following is the definition of the input parameter "UserMayNotChangePassword". - /// Specifies whether the user is allowed to change the password on this - /// account. The default value is True. - /// - [Parameter(ValueFromPipelineByPropertyName = true)] - public System.Management.Automation.SwitchParameter UserMayNotChangePassword - { - get { return this.usermaynotchangepassword;} - - set { this.usermaynotchangepassword = value; } - } - - private System.Management.Automation.SwitchParameter usermaynotchangepassword; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) - { - InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); - ThrowTerminatingError(ex.MakeErrorRecord()); - } - - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - if (CheckShouldProcess(Name)) - { - var user = new LocalUser - { - Name = Name, - Description = Description, - Enabled = true, - FullName = FullName, - UserMayChangePassword = true - }; - - foreach (var paramName in parameterNames) - { - if (this.HasParameter(paramName)) - { - switch (paramName) - { - case "AccountExpires": - user.AccountExpires = AccountExpires; - break; - - case "Disabled": - user.Enabled = !Disabled; - break; - - case "UserMayNotChangePassword": - user.UserMayChangePassword = !UserMayNotChangePassword; - break; - } - } - } - - if (AccountNeverExpires.IsPresent) - user.AccountExpires = null; - - // Password will be null if NoPassword was given - user = sam.CreateLocalUser(user, Password, PasswordNeverExpires.IsPresent); - - WriteObject(user); - } - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionNewUser); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs deleted file mode 100644 index 981643cf04c..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Remove-LocalGroup cmdlet deletes a security group from the Windows - /// Security Accounts manager. - /// - [Cmdlet(VerbsCommon.Remove, "LocalGroup", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717975")] - [Alias("rlg")] - public class RemoveLocalGroupCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies security groups from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalGroup[] InputObject - { - get { return this.inputobject; } - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup[] inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local groups to be deleted from the local Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies the LocalGroup accounts to remove by - /// System.Security.Principal.SecurityIdentifier. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid; } - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessGroups(); - ProcessNames(); - ProcessSids(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process groups requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var name in Name) - { - try - { - if (CheckShouldProcess(name)) - sam.RemoveLocalGroup(sam.GetLocalGroup(name)); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process groups requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var sid in SID) - { - try - { - if (CheckShouldProcess(sid.ToString())) - sam.RemoveLocalGroup(sid); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process groups given through -InputObject. - /// - private void ProcessGroups() - { - if (InputObject != null) - { - foreach (var group in InputObject) - { - try - { - if (CheckShouldProcess(group.Name)) - sam.RemoveLocalGroup(group); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionRemoveGroup); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs deleted file mode 100644 index 47d0a77784e..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Collections.Generic; -using System.Management.Automation; -using System.Security.Principal; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Remove-LocalGroupMember cmdlet removes one or more members (users or - /// groups) from a local security group. - /// - [Cmdlet(VerbsCommon.Remove, "LocalGroupMember", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717989")] - [Alias("rlgm")] - public class RemoveLocalGroupMemberCommand : PSCmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Group". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "Group")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalGroup Group - { - get { return this.group;} - - set { this.group = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup group; - - /// - /// The following is the definition of the input parameter "Member". - /// Specifies one or more users or groups to remove from this local group. You can - /// identify users or groups by specifying their names or SIDs, or by passing - /// Microsoft.PowerShell.Commands.LocalPrincipal objects. - /// - [Parameter(Mandatory = true, - Position = 1, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalPrincipal[] Member - { - get { return this.member;} - - set { this.member = value; } - } - - private Microsoft.PowerShell.Commands.LocalPrincipal[] member; - - /// - /// The following is the definition of the input parameter "Name". - /// The security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - if (Group != null) - ProcessGroup(Group); - else if (Name != null) - ProcessName(Name); - else if (SID != null) - ProcessSid(SID); - } - catch (GroupNotFoundException ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - - /// - /// Creates a list of objects - /// ready to be processed by the cmdlet. - /// - /// - /// Name or SID (as a string) of the group we'll be removing from. - /// This string is used primarily for specifying the target - /// in WhatIf scenarios. - /// - /// - /// LocalPrincipal object to be processed - /// - /// - /// LocalPrincipal object processed and ready to be removed - /// - /// - /// - /// LocalPrincipal object in the Member parameter may not be complete, - /// particularly those created from a name or a SID string given to the - /// Member cmdlet parameter. The object returned from this method contains at the very least, contain a valid SID. - /// - /// - /// Any Member object provided by name or SID string will be looked up - /// to ensure that such an object exists. If an object is not found, - /// an error message is displayed by PowerShell and null will be returned from this method - /// - /// - /// This method also handles the WhatIf scenario. If the Cmdlet's - /// ShouldProcess method returns false on any Member object - /// - /// - private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) - { - LocalPrincipal principal = null; - - // if the member has a SID, we can use it directly - if (member.SID != null) - { - principal = member; - } - else // otherwise it must have been constructed by name - { - SecurityIdentifier sid = this.TrySid(member.Name); - - if (sid != null) - { - member.SID = sid; - principal = member; - } - else - { - try - { - principal = sam.LookupAccount(member.Name); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - if (CheckShouldProcess(principal, groupId)) - return principal; - - return null; - } - - /// - /// Determine if a principal should be processed. - /// Just a wrapper around Cmdlet.ShouldProcess, with localized string - /// formatting. - /// - /// Name of the principal to be removed. - /// - /// Name of the group from which the members will be removed. - /// - /// - /// True if the principal should be processed, false otherwise. - /// - private bool CheckShouldProcess(LocalPrincipal principal, string groupName) - { - if (principal == null) - return false; - - string msg = StringUtil.Format(Strings.ActionRemoveGroupMember, principal.ToString()); - - return ShouldProcess(groupName, msg); - } - - /// - /// Remove members from a group. - /// - /// - /// A object representing the group from which - /// the members will be removed. - /// - private void ProcessGroup(LocalGroup group) - { - string groupId = group.Name ?? group.SID.ToString(); - foreach (var member in this.Member) - { - LocalPrincipal principal = MakePrincipal(groupId, member); - if (principal != null) - { - var ex = sam.RemoveLocalGroupMember(group, principal); - if (ex != null) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Remove members from a group specified by name. - /// - /// - /// The name of the group from which the members will be removed. - /// - private void ProcessName(string name) - { - ProcessGroup(sam.GetLocalGroup(name)); - } - - /// - /// Remove members from a group specified by SID. - /// - /// - /// A object identifying the group - /// from which the members will be removed. - /// - private void ProcessSid(SecurityIdentifier groupSid) - { - foreach (var member in this.Member) - { - LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); - if (principal != null) - { - var ex = sam.RemoveLocalGroupMember(groupSid, principal); - if (ex != null) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs deleted file mode 100644 index 6d6081fef7e..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Remove-LocalUser cmdlet deletes a user account from the Windows Security - /// Accounts manager. - /// - [Cmdlet(VerbsCommon.Remove, "LocalUser", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717982")] - [Alias("rlu")] - public class RemoveLocalUserCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local user accounts to remove in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Microsoft.PowerShell.Commands.LocalUser[] InputObject - { - get { return this.inputobject;} - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalUser[] inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the user accounts to be deleted from the local Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return this.name; } - - set { this.name = value; } - } - - private string[] name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies the local user accounts to remove by - /// System.Security.Principal.SecurityIdentifier. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public System.Security.Principal.SecurityIdentifier[] SID - { - get { return this.sid; } - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier[] sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessUsers(); - ProcessNames(); - ProcessSids(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process users requested by -Name. - /// - /// - /// All arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessNames() - { - if (Name != null) - { - foreach (var name in Name) - { - try - { - if (CheckShouldProcess(name)) - sam.RemoveLocalUser(sam.GetLocalUser(name)); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users requested by -SID. - /// - private void ProcessSids() - { - if (SID != null) - { - foreach (var sid in SID) - { - try - { - if (CheckShouldProcess(sid.ToString())) - sam.RemoveLocalUser(sid); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - /// - /// Process users given through -InputObject. - /// - private void ProcessUsers() - { - if (InputObject != null) - { - foreach (var user in InputObject) - { - try - { - if (CheckShouldProcess(user.Name)) - sam.RemoveLocalUser(user); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - } - - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionRemoveUser); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs deleted file mode 100644 index c594fccb889..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Rename-LocalGroup cmdlet renames a local security group in the Security - /// Accounts Manager. - /// - [Cmdlet(VerbsCommon.Rename, "LocalGroup", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717978")] - [Alias("rnlg")] - public class RenameLocalGroupCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local group account to rename in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNullOrEmpty] - public Microsoft.PowerShell.Commands.LocalGroup InputObject - { - get { return this.inputobject;} - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local group to be renamed in the local Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "NewName". - /// Specifies the new name for the local security group in the Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 1)] - [ValidateNotNullOrEmpty] - public string NewName - { - get { return this.newname;} - - set { this.newname = value; } - } - - private string newname; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNullOrEmpty] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessGroup(); - ProcessName(); - ProcessSid(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process group requested by -Name. - /// - /// - /// Arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessName() - { - if (Name != null) - { - try - { - if (CheckShouldProcess(Name, NewName)) - sam.RenameLocalGroup(sam.GetLocalGroup(Name), NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Process group requested by -SID. - /// - private void ProcessSid() - { - if (SID != null) - { - try - { - if (CheckShouldProcess(SID.ToString(), NewName)) - sam.RenameLocalGroup(SID, NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Process group given through -InputObject. - /// - private void ProcessGroup() - { - if (InputObject != null) - { - try - { - if (CheckShouldProcess(InputObject.Name, NewName)) - sam.RenameLocalGroup(InputObject, NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Determine if a group should be processed. - /// Just a wrapper around Cmdlet.ShouldProcess, with localized string - /// formatting. - /// - /// - /// Name of the group to rename. - /// - /// - /// New name for the group. - /// - /// - /// True if the group should be processed, false otherwise. - /// - private bool CheckShouldProcess(string groupName, string newName) - { - string msg = StringUtil.Format(Strings.ActionRenameGroup, newName); - - return ShouldProcess(groupName, msg); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs deleted file mode 100644 index c23cf41ac61..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Rename-LocalUser cmdlet renames a local user account in the Security - /// Accounts Manager. - /// - [Cmdlet(VerbsCommon.Rename, "LocalUser", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=717983")] - [Alias("rnlu")] - public class RenameLocalUserCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local user account to rename in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalUser InputObject - { - get { return this.inputobject;} - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalUser inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local user account to be renamed in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "NewName". - /// Specifies the new name for the local user account in the Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 1)] - [ValidateNotNullOrEmpty] - public string NewName - { - get { return this.newname;} - - set { this.newname = value; } - } - - private string newname; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies the local user to rename. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - ProcessUser(); - ProcessName(); - ProcessSid(); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - /// - /// Process user requested by -Name. - /// - /// - /// Arguments to -Name will be treated as names, - /// even if a name looks like a SID. - /// - private void ProcessName() - { - if (Name != null) - { - try - { - if (CheckShouldProcess(Name, NewName)) - sam.RenameLocalUser(sam.GetLocalUser(Name), NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Process user requested by -SID. - /// - private void ProcessSid() - { - if (SID != null) - { - try - { - if (CheckShouldProcess(SID.ToString(), NewName)) - sam.RenameLocalUser(SID, NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Process group given through -InputObject. - /// - private void ProcessUser() - { - if (InputObject != null) - { - try - { - if (CheckShouldProcess(InputObject.Name, NewName)) - sam.RenameLocalUser(InputObject, NewName); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - } - - /// - /// Determine if a user should be processed. - /// Just a wrapper around Cmdlet.ShouldProcess, with localized string - /// formatting. - /// - /// - /// Name of the user to rename. - /// - /// - /// New name for the user. - /// - /// - /// True if the user should be processed, false otherwise. - /// - private bool CheckShouldProcess(string userName, string newName) - { - string msg = StringUtil.Format(Strings.ActionRenameUser, newName); - - return ShouldProcess(userName, msg); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs deleted file mode 100644 index 49ae31dacc7..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Set-LocalGroup cmdlet modifies the properties of a local security group - /// in the Windows Security Accounts Manager. - /// - [Cmdlet(VerbsCommon.Set, "LocalGroup", - SupportsShouldProcess = true, - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717979")] - [Alias("slg")] - public class SetLocalGroupCommand : Cmdlet - { - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "Description". - /// A descriptive comment. - /// - [Parameter(Mandatory = true)] - [ValidateNotNull] - public string Description - { - get { return this.description;} - - set { this.description = value; } - } - - private string description; - - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the local group account to modify in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalGroup InputObject - { - get { return this.inputobject;} - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalGroup inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local group to be renamed in the local Security Accounts - /// Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Default")] - [ValidateNotNull] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a security group from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - LocalGroup group = null; - - if (InputObject != null) - { - if (CheckShouldProcess(InputObject.ToString())) - group = InputObject; - } - else if (Name != null) - { - group = sam.GetLocalGroup(Name); - - if (!CheckShouldProcess(Name)) - group = null; - } - else if (SID != null) - { - group = sam.GetLocalGroup(SID); - - if (!CheckShouldProcess(SID.ToString())) - group = null; - } - - if (group != null) - { - var delta = group.Clone(); - - delta.Description = Description; - sam.UpdateLocalGroup(group, delta); - } - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionSetGroup); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs deleted file mode 100644 index 3bfdc24ac03..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#region Using directives -using System; -using System.Management.Automation; - -using System.Management.Automation.SecurityAccountsManager; -using System.Management.Automation.SecurityAccountsManager.Extensions; - -using Microsoft.PowerShell.LocalAccounts; -#endregion - -namespace Microsoft.PowerShell.Commands -{ - /// - /// The Set-LocalUser cmdlet changes the properties of a user account in the - /// local Windows Security Accounts Manager. It can also reset the password of a - /// local user account. - /// - [Cmdlet(VerbsCommon.Set, "LocalUser", - SupportsShouldProcess = true, - DefaultParameterSetName = "Name", - HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717984")] - [Alias("slu")] - public class SetLocalUserCommand : PSCmdlet - { - #region Static Data - // Names of object- and boolean-type parameters. - // Switch parameters don't need to be included. - private static string[] parameterNames = new string[] - { - "AccountExpires", - "Description", - "FullName", - "Password", - "UserMayChangePassword", - "PasswordNeverExpires" - }; - #endregion Static Data - - #region Instance Data - private Sam sam = null; - #endregion Instance Data - - #region Parameter Properties - /// - /// The following is the definition of the input parameter "AccountExpires". - /// Specifies when the user account will expire. Set to null to indicate that - /// the account will never expire. The default value is null (account never - /// expires). - /// - [Parameter] - public System.DateTime AccountExpires - { - get { return this.accountexpires;} - - set { this.accountexpires = value; } - } - - private System.DateTime accountexpires; - - /// - /// The following is the definition of the input parameter "AccountNeverExpires". - /// Specifies that the account will not expire. - /// - [Parameter] - public System.Management.Automation.SwitchParameter AccountNeverExpires - { - get { return this.accountneverexpires;} - - set { this.accountneverexpires = value; } - } - - private System.Management.Automation.SwitchParameter accountneverexpires; - - /// - /// The following is the definition of the input parameter "Description". - /// A descriptive comment for this user account. - /// - [Parameter] - [ValidateNotNull] - public string Description - { - get { return this.description;} - - set { this.description = value; } - } - - private string description; - - /// - /// The following is the definition of the input parameter "FullName". - /// Specifies the full name of the user account. This is different from the - /// username of the user account. - /// - [Parameter] - [ValidateNotNull] - public string FullName - { - get { return this.fullname;} - - set { this.fullname = value; } - } - - private string fullname; - /// - /// The following is the definition of the input parameter "InputObject". - /// Specifies the of the local user account to modify in the local Security - /// Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "InputObject")] - [ValidateNotNull] - public Microsoft.PowerShell.Commands.LocalUser InputObject - { - get { return this.inputobject;} - - set { this.inputobject = value; } - } - - private Microsoft.PowerShell.Commands.LocalUser inputobject; - - /// - /// The following is the definition of the input parameter "Name". - /// Specifies the local user account to change. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "Name")] - [ValidateNotNullOrEmpty] - public string Name - { - get { return this.name;} - - set { this.name = value; } - } - - private string name; - - /// - /// The following is the definition of the input parameter "Password". - /// Specifies the password for the local user account. - /// - [Parameter] - [ValidateNotNull] - public System.Security.SecureString Password - { - get { return this.password;} - - set { this.password = value; } - } - - private System.Security.SecureString password; - - /// - /// The following is the definition of the input parameter "PasswordNeverExpires". - /// Specifies that the password will not expire. - /// - [Parameter] - public bool PasswordNeverExpires - { - get { return this.passwordneverexpires; } - - set { this.passwordneverexpires = value; } - } - - private bool passwordneverexpires; - - /// - /// The following is the definition of the input parameter "SID". - /// Specifies a user from the local Security Accounts Manager. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = "SecurityIdentifier")] - [ValidateNotNull] - public System.Security.Principal.SecurityIdentifier SID - { - get { return this.sid;} - - set { this.sid = value; } - } - - private System.Security.Principal.SecurityIdentifier sid; - - /// - /// The following is the definition of the input parameter "UserMayChangePassword". - /// Specifies whether the user is allowed to change the password on this - /// account. The default value is True. - /// - [Parameter] - public bool UserMayChangePassword - { - get { return this.usermaychangepassword;} - - set { this.usermaychangepassword = value; } - } - - private bool usermaychangepassword; - #endregion Parameter Properties - - #region Cmdlet Overrides - /// - /// BeginProcessing method. - /// - protected override void BeginProcessing() - { - if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) - { - InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); - ThrowTerminatingError(ex.MakeErrorRecord()); - } - - sam = new Sam(); - } - - /// - /// ProcessRecord method. - /// - protected override void ProcessRecord() - { - try - { - LocalUser user = null; - - if (InputObject != null) - { - if (CheckShouldProcess(InputObject.ToString())) - user = InputObject; - } - else if (Name != null) - { - user = sam.GetLocalUser(Name); - - if (!CheckShouldProcess(Name)) - user = null; - } - else if (SID != null) - { - user = sam.GetLocalUser(SID); - - if (!CheckShouldProcess(SID.ToString())) - user = null; - } - - if (user == null) - return; - - // We start with what already exists - var delta = user.Clone(); - bool? passwordNeverExpires = null; - - foreach (var paramName in parameterNames) - { - if (this.HasParameter(paramName)) - { - switch (paramName) - { - case "AccountExpires": - delta.AccountExpires = this.AccountExpires; - break; - - case "Description": - delta.Description = this.Description; - break; - - case "FullName": - delta.FullName = this.FullName; - break; - - case "UserMayChangePassword": - delta.UserMayChangePassword = this.UserMayChangePassword; - break; - - case "PasswordNeverExpires": - passwordNeverExpires = this.PasswordNeverExpires; - break; - } - } - } - - if (AccountNeverExpires.IsPresent) - delta.AccountExpires = null; - - sam.UpdateLocalUser(user, delta, Password, passwordNeverExpires); - } - catch (Exception ex) - { - WriteError(ex.MakeErrorRecord()); - } - } - - /// - /// EndProcessing method. - /// - protected override void EndProcessing() - { - if (sam != null) - { - sam.Dispose(); - sam = null; - } - } - #endregion Cmdlet Overrides - - #region Private Methods - private bool CheckShouldProcess(string target) - { - return ShouldProcess(target, Strings.ActionSetUser); - } - #endregion Private Methods - } - -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs deleted file mode 100644 index 1c7a7630ea3..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs +++ /dev/null @@ -1,689 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management.Automation; -using System.Management.Automation.SecurityAccountsManager; -using System.Runtime.Serialization; - -using Microsoft.PowerShell.LocalAccounts; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Base class for cmdlet-specific exceptions. - /// - public class LocalAccountsException : Exception - { -#region Public Properties - /// - /// Gets the - /// value for this exception. - /// - public ErrorCategory ErrorCategory - { - get; - private set; - } - - /// - /// Gets the target object for this exception. This is used as - /// the TargetObject member of a PowerShell - /// object. - /// - public object Target - { - get; - private set; - } - - /// - /// Gets the error name. This is used as the ErrorId parameter when - /// constructing a PowerShell - /// oject. - /// - public string ErrorName - { - get - { - string exname = "Exception"; - var exlen = exname.Length; - var name = this.GetType().Name; - - if (name.EndsWith(exname, StringComparison.OrdinalIgnoreCase) && name.Length > exlen) - name = name.Substring(0, name.Length - exlen); - return name; - } - } -#endregion Public Properties - - internal LocalAccountsException(string message, object target, ErrorCategory errorCategory) - : base(message) - { - ErrorCategory = errorCategory; - Target = target; - } - - /// - /// Compliance Constructor. - /// - public LocalAccountsException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public LocalAccountsException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public LocalAccountsException(string message, Exception ex) : base(message, ex) { } - - /// - /// Compliance Constructor. - /// - /// - /// - protected LocalAccountsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating an error occurred during one of the internal - /// operations such as opening or closing a handle. - /// - public class InternalException : LocalAccountsException - { -#region Public Properties - /// - /// Gets the NTSTATUS code for this exception. - /// - public UInt32 StatusCode - { - get; - private set; - } -#endregion Public Properties - - internal InternalException(UInt32 ntStatus, - string message, - object target, - ErrorCategory errorCategory = ErrorCategory.NotSpecified) - : base(message, target, errorCategory) - { - StatusCode = ntStatus; - } - - internal InternalException(UInt32 ntStatus, - object target, - ErrorCategory errorCategory = ErrorCategory.NotSpecified) - : this(ntStatus, - StringUtil.Format(Strings.UnspecifiedErrorNtStatus, ntStatus), - target, - errorCategory) - { - } - - /// - /// Compliance Constructor. - /// - public InternalException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public InternalException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public InternalException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected InternalException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating an error occurred when a native function - /// is called that returns a Win32 error code as opposed to an - /// NT Status code. - /// - public class Win32InternalException : LocalAccountsException - { -#region Public Properties - /// - /// The Win32 error code for this exception. - /// - public int NativeErrorCode - { - get; - private set; - } -#endregion Public Properties - - internal Win32InternalException(int errorCode, - string message, - object target, - ErrorCategory errorCategory = ErrorCategory.NotSpecified) - : base(message, target, errorCategory) - { - NativeErrorCode = errorCode; - } - - internal Win32InternalException(int errorCode, - object target, - ErrorCategory errorCategory = ErrorCategory.NotSpecified) - : this(errorCode, - StringUtil.Format(Strings.UnspecifiedErrorWin32Error, errorCode), - target, - errorCategory) - { - } - - /// - /// Compliance Constructor. - /// - public Win32InternalException() : base() {} - /// - /// Compliance Constructor. - /// - /// - public Win32InternalException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public Win32InternalException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected Win32InternalException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating an invalid password. - /// - public class InvalidPasswordException : LocalAccountsException - { - /// - /// Generates with a default invalid password message. - /// - public InvalidPasswordException() - : base(Strings.InvalidPassword, null, ErrorCategory.InvalidArgument) - { - } - - /// - /// Generates the exception with the specified message. - /// - /// - public InvalidPasswordException(string message) - : base(message, null, ErrorCategory.InvalidArgument) - { - } - - /// - /// Creates a message from the specified error code. - /// - /// - public InvalidPasswordException(uint errorCode) - : base(StringUtil.GetSystemMessage(errorCode), null, ErrorCategory.InvalidArgument) - { - } - - /// - /// Compliance Constructor. - /// - /// - /// - public InvalidPasswordException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected InvalidPasswordException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception thrown when invalid parameter pairing is detected. - /// - public class InvalidParametersException : LocalAccountsException - { - /// - /// Creates InvalidParametersException using the specified message. - /// - /// - public InvalidParametersException(string message) - : base(message, null, ErrorCategory.InvalidArgument) - { - } - - internal InvalidParametersException(string parameterA, string parameterB) - : this(StringUtil.Format(Strings.InvalidParameterPair, parameterA, parameterB)) - { - } - - /// - /// Compliance Constructor. - /// - public InvalidParametersException() : base() { } - /// - /// Compliance Constructor. - /// - /// - /// - public InvalidParametersException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected InvalidParametersException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating permission denied. - /// - public class AccessDeniedException : LocalAccountsException - { - internal AccessDeniedException(object target) - : base(Strings.AccessDenied, target, ErrorCategory.PermissionDenied) - { - } - - /// - /// Compliance Constructor. - /// - public AccessDeniedException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public AccessDeniedException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public AccessDeniedException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected AccessDeniedException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that the name of a user or group is invalid. - /// - public class InvalidNameException : LocalAccountsException - { - internal InvalidNameException(string name, object target) - : base(StringUtil.Format(Strings.InvalidName, name), target, ErrorCategory.InvalidArgument) - { - } - - /// - /// Compliance Constructor. - /// - public InvalidNameException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public InvalidNameException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public InvalidNameException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected InvalidNameException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that the specified name is already in use. - /// - public class NameInUseException : LocalAccountsException - { - internal NameInUseException(string name, object target) - : base(StringUtil.Format(Strings.NameInUse, name), target, ErrorCategory.InvalidArgument) - { - } - - /// - /// Compliance Constructor. - /// - public NameInUseException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public NameInUseException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public NameInUseException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected NameInUseException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that an entity of some kind was not found. - /// Also serves as a base class for more specific object-not-found errors. - /// - public class NotFoundException : LocalAccountsException - { - internal NotFoundException(string message, object target) - : base(message, target, ErrorCategory.ObjectNotFound) - { - } - - /// - /// Compliance Constructor. - /// - public NotFoundException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public NotFoundException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public NotFoundException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected NotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a principal was not Found. - /// - public class PrincipalNotFoundException : NotFoundException - { - internal PrincipalNotFoundException(string principal, object target) - : base(StringUtil.Format(Strings.PrincipalNotFound, principal), target) - { - } - - /// - /// Compliance Constructor. - /// - public PrincipalNotFoundException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public PrincipalNotFoundException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public PrincipalNotFoundException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected PrincipalNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a group was not found. - /// - public class GroupNotFoundException : NotFoundException - { - internal GroupNotFoundException(string group, object target) - : base(StringUtil.Format(Strings.GroupNotFound, group), target) - { - } - - /// - /// Compliance Constructor. - /// - public GroupNotFoundException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public GroupNotFoundException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public GroupNotFoundException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected GroupNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a user was not found. - /// - public class UserNotFoundException : NotFoundException - { - internal UserNotFoundException(string user, object target) - : base(StringUtil.Format(Strings.UserNotFound, user), target) - { - } - - /// - /// Compliance Constructor. - /// - public UserNotFoundException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public UserNotFoundException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public UserNotFoundException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected UserNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a group member was not found. - /// - public class MemberNotFoundException : NotFoundException - { - internal MemberNotFoundException(string member, string group) - : base(StringUtil.Format(Strings.MemberNotFound, member, group), member) - { - } - - /// - /// Compliance Constructor. - /// - public MemberNotFoundException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public MemberNotFoundException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public MemberNotFoundException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected MemberNotFoundException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that an entity of some kind already exists. - /// Also serves as a base class for more specific object-exists errors. - /// - public class ObjectExistsException : LocalAccountsException - { - internal ObjectExistsException(string message, object target) - : base(message, target, ErrorCategory.ResourceExists) - { - } - - /// - /// Compliance Constructor. - /// - public ObjectExistsException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public ObjectExistsException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public ObjectExistsException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected ObjectExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a group already exists. - /// - public class GroupExistsException : ObjectExistsException - { - internal GroupExistsException(string group, object target) - : base(StringUtil.Format(Strings.GroupExists, group), target) - { - } - - /// - /// Compliance Constructor. - /// - public GroupExistsException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public GroupExistsException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public GroupExistsException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected GroupExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that a group already exists. - /// - public class UserExistsException : ObjectExistsException - { - internal UserExistsException(string user, object target) - : base(StringUtil.Format(Strings.UserExists, user), target) - { - } - - /// - /// Compliance Constructor. - /// - public UserExistsException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public UserExistsException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public UserExistsException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected UserExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } - - /// - /// Exception indicating that an object already exists as a group member. - /// - public class MemberExistsException : ObjectExistsException - { - internal MemberExistsException(string member, string group, object target) - : base(StringUtil.Format(Strings.MemberExists, member, group), target) - { - } - - /// - /// Compliance Constructor. - /// - public MemberExistsException() : base() { } - /// - /// Compliance Constructor. - /// - /// - public MemberExistsException(string message) : base(message) { } - /// - /// Compliance Constructor. - /// - /// - /// - public MemberExistsException(string message, Exception ex) : base(message, ex) { } - /// - /// Compliance Constructor. - /// - /// - /// - protected MemberExistsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { } - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs deleted file mode 100644 index 007966cb0a8..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using System.Security; -using System.Security.Principal; -using System.Text.RegularExpressions; - -using Microsoft.PowerShell.Commands; -using Microsoft.PowerShell.LocalAccounts; - -namespace System.Management.Automation.SecurityAccountsManager.Extensions -{ - /// - /// Provides extension methods for the Cmdlet class. - /// - internal static class CmdletExtensions - { - /// - /// Attempt to create a SID from a string. - /// - /// The cmdlet being extended with this method. - /// The string to be converted to a SID. - /// - /// A boolean indicating whether SID constants, such as "BA", are considered. - /// - /// - /// A object if the conversion was successful, - /// null otherwise. - /// - internal static SecurityIdentifier TrySid(this Cmdlet cmdlet, - string s, - bool allowSidConstants = false) - { - if (!allowSidConstants) - if (!(s.Length > 2 && s.StartsWith("S-", StringComparison.Ordinal) && char.IsDigit(s[2]))) - return null; - - SecurityIdentifier sid = null; - - try - { - sid = new SecurityIdentifier(s); - } - catch (ArgumentException) - { - // do nothing here, just fall through to the return - } - - return sid; - } - } - - /// - /// Provides extension methods for the PSCmdlet class. - /// - internal static class PSExtensions - { - /// - /// Determine if a given parameter was provided to the cmdlet. - /// - /// - /// The object to check. - /// - /// - /// A string containing the name of the parameter. This should be in the - /// same letter-casing as the defined parameter. - /// - /// - /// True if the specified parameter was given on the cmdlet invocation, - /// false otherwise. - /// - internal static bool HasParameter(this PSCmdlet cmdlet, string parameterName) - { - var invocation = cmdlet.MyInvocation; - if (invocation != null) - { - var parameters = invocation.BoundParameters; - - if (parameters != null) - { - // PowerShell sets the parameter names in the BoundParameters dictionary - // to their "proper" casing, so we don't have to do a case-insensitive search. - if (parameters.ContainsKey(parameterName)) - return true; - } - } - - return false; - } - } - - /// - /// Provides extension methods for the SecurityIdentifier class. - /// - internal static class SidExtensions - { - /// - /// Get the Relative ID (RID) from a object. - /// - /// The SecurityIdentifier containing the desired Relative ID. - /// - /// A UInt32 value containing the Relative ID in the SecurityIdentifier. - /// - internal static UInt32 GetRid(this SecurityIdentifier sid) - { - byte[] sidBinary = new byte[sid.BinaryLength]; - sid.GetBinaryForm(sidBinary, 0); - - return System.BitConverter.ToUInt32(sidBinary, sidBinary.Length-4); - } - - /// - /// Gets the Identifier Authority portion of a - /// - /// The SecurityIdentifier containing the desired Authority. - /// - /// A long integer value containing the SecurityIdentifier's Identifier Authority value. - /// - /// - /// This method is used primarily for determining the Source of a Principal. - /// The Win32 API LsaLookupUserAccountType function does not (yet) properly - /// identify MicrosoftAccount principals. - /// - internal static long GetIdentifierAuthority(this SecurityIdentifier sid) - { - byte[] sidBinary = new byte[sid.BinaryLength]; - - sid.GetBinaryForm(sidBinary, 0); - - // The Identifier Authority is six bytes wide, - // in big-endian format, starting at the third byte - long authority = (long) (((long)sidBinary[2]) << 40) + - (((long)sidBinary[3]) << 32) + - (((long)sidBinary[4]) << 24) + - (((long)sidBinary[5]) << 16) + - (((long)sidBinary[6]) << 8) + - (((long)sidBinary[7]) ); - - return authority; - } - - internal static bool IsMsaAccount(this SecurityIdentifier sid) - { - return sid.GetIdentifierAuthority() == 11; - } - } - - internal static class SecureStringExtensions - { - /// - /// Extension method to extract clear text from a - /// object. - /// - /// - /// This SecureString object, containing encrypted text. - /// - /// - /// A string containing the SecureString object's original text. - /// - internal static string AsString(this SecureString str) - { -#if CORECLR - IntPtr buffer = SecureStringMarshal.SecureStringToCoTaskMemUnicode(str); - string clear = Marshal.PtrToStringUni(buffer); - Marshal.ZeroFreeCoTaskMemUnicode(buffer); -#else - var bstr = Marshal.SecureStringToBSTR(str); - string clear = Marshal.PtrToStringAuto(bstr); - Marshal.ZeroFreeBSTR(bstr); -#endif - return clear; - } - } - - internal static class ExceptionExtensions - { - internal static ErrorRecord MakeErrorRecord(this Exception ex, - string errorId, - ErrorCategory errorCategory, - object target = null) - { - return new ErrorRecord(ex, errorId, errorCategory, target); - } - - internal static ErrorRecord MakeErrorRecord(this Exception ex, object target = null) - { - // This part is somewhat less than beautiful, but it prevents - // having to have multiple exception handlers in every cmdlet command. - var exTemp = ex as LocalAccountsException; - - if (exTemp != null) - return MakeErrorRecord(exTemp, target ?? exTemp.Target); - - return new ErrorRecord(ex, - Strings.UnspecifiedError, - ErrorCategory.NotSpecified, - target); - } - - internal static ErrorRecord MakeErrorRecord(this LocalAccountsException ex, object target = null) - { - return ex.MakeErrorRecord(ex.ErrorName, ex.ErrorCategory, target ?? ex.Target); - } - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs deleted file mode 100644 index b43904fb773..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -using Microsoft.PowerShell.LocalAccounts; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Describes a Local Group. - /// Objects of this type are provided to and returned from group-related Cmdlets. - /// - public class LocalGroup : LocalPrincipal - { - #region Public Properties - /// - /// A short description of the Group. - /// - public string Description { get; set; } - #endregion Public Properties - - #region Construction - /// - /// Initializes a new LocalGroup object. - /// - public LocalGroup() - { - ObjectClass = Strings.ObjectClassGroup; - } - - /// - /// Initializes a new LocalUser object with the specified name. - /// - /// Name of the new LocalGroup. - public LocalGroup(string name) - : base(name) - { - ObjectClass = Strings.ObjectClassGroup; - } - - /// - /// Construct a new LocalGroup object that is a copy of another. - /// - /// - private LocalGroup(LocalGroup other) - : this(other.Name) - { - Description = other.Description; - } - #endregion Construction - - #region Public Methods - /// - /// Provides a string representation of the LocalGroup object. - /// - /// - /// A string containing the Group Name. - /// - public override string ToString() - { - return Name ?? SID.ToString(); - } - - /// - /// Create a copy of a LocalGroup object. - /// - /// - /// A new LocalGroup object with the same property values as this one. - /// - public LocalGroup Clone() - { - return new LocalGroup(this); - } - #endregion Public Methods - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs deleted file mode 100644 index dcfec24631b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Security.Principal; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Defines the source of a Principal. - /// - public enum PrincipalSource - { - /// - /// The principal source is unknown or could not be determined. - /// - Unknown = 0, - - /// - /// The principal is sourced from the local Windows Security Accounts Manager. - /// - Local, - - /// - /// The principal is sourced from an Active Directory domain. - /// - ActiveDirectory, - - /// - /// The principal is sourced from Azure Active Directory. - /// - AzureAD, - - /// - /// The principal is a Microsoft Account, such as - /// MicrosoftAccount\user@domain.com - /// - MicrosoftAccount - } - - /// - /// Represents a Principal. Serves as a base class for Users and Groups. - /// - public class LocalPrincipal - { - #region Public Properties - /// - /// The account name of the Principal. - /// - public string Name { get; set; } - - /// - /// The Security Identifier that uniquely identifies the Principal/ - /// - public SecurityIdentifier SID { get; set; } - - /// - /// Indicates the account store from which the principal is sourced. - /// One of the PrincipalSource enumerations. - /// - public PrincipalSource? PrincipalSource { get; set; } - - /// - /// The object class that represents this principal. - /// This can be User or Group. - /// - public string ObjectClass { get; set; } - #endregion Public Properties - - #region Construction - /// - /// Initializes a new LocalPrincipal object. - /// - public LocalPrincipal() - { - } - - /// - /// Initializes a new LocalPrincipal object with the specified name. - /// - /// Name of the new LocalPrincipal. - public LocalPrincipal(string name) - { - Name = name; - } - #endregion Construction - - #region Public Methods - /// - /// Provides a string representation of the Principal. - /// - /// - /// A string, in SDDL form, representing the Principal. - /// - public override string ToString() - { - return Name ?? SID.ToString(); - } - #endregion Public Methods - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs deleted file mode 100644 index 9cad9777cac..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; - -using Microsoft.PowerShell.LocalAccounts; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// Describes a Local User. - /// Objects of this type are provided to and returned from user-related Cmdlets. - /// - public class LocalUser : LocalPrincipal - { - #region Public Properties - /// - /// The date and time at which this user account expires. - /// A value of null indicates that the account never expires. - /// - public DateTime? AccountExpires { get; set; } - - /// - /// A short description of the User. - /// - public string Description { get; set; } - - /// - /// Indicates whether the user account is enabled (true) or disabled (false). - /// - public bool Enabled { get; set; } - - /// - /// The user's full name. Not the same as the User name. - /// - public string FullName { get; set; } - - /// - /// The date and time at which this user account password is allowed - /// to be changed. The password cannot be changed before this time. - /// A value of null indicates that the password can be changed anytime. - /// - public DateTime? PasswordChangeableDate { get; set; } - - /// - /// The date and time at which this user account password must be changed - /// to a new password. A value of null indicates that the password will - /// never expire. - /// - public DateTime? PasswordExpires { get; set; } - - /// - /// Indicates whether the user is allowed to change the password (true) - /// or not (false). - /// - public bool UserMayChangePassword { get; set; } - - /// - /// Indicates whether the user must have a password (true) or not (false). - /// - public bool PasswordRequired { get; set; } - - /// - /// The date and time at which this user last changed the account password. - /// - public DateTime? PasswordLastSet { get; set; } - - /// - /// The date and time at which the user last logged on to the machine. - /// - public DateTime? LastLogon { get; set; } - #endregion Public Properties - - #region Construction - /// - /// Initializes a new LocalUser object. - /// - public LocalUser() - { - ObjectClass = Strings.ObjectClassUser; - } - - /// - /// Initializes a new LocalUser object with the specified name. - /// - /// Name of the new LocalUser. - public LocalUser(string name) - : base(name) - { - ObjectClass = Strings.ObjectClassUser; - } - - /// - /// Construct a new LocalUser object that is a copy of another. - /// - /// The LocalUser object to copy. - private LocalUser(LocalUser other) - : this(other.Name) - { - SID = other.SID; - PrincipalSource = other.PrincipalSource; - ObjectClass = other.ObjectClass; - - AccountExpires = other.AccountExpires; - Description = other.Description; - Enabled = other.Enabled; - FullName = other.FullName; - PasswordChangeableDate = other.PasswordChangeableDate; - PasswordExpires = other.PasswordExpires; - UserMayChangePassword = other.UserMayChangePassword; - - PasswordRequired = other.PasswordRequired; - PasswordLastSet = other.PasswordLastSet; - LastLogon = other.LastLogon; - } - #endregion Construction - - #region Public Methods - /// - /// Provides a string representation of the LocalUser object. - /// - /// - /// A string containing the User Name. - /// - public override string ToString() - { - return Name ?? SID.ToString(); - } - - /// - /// Create a copy of a LocalUser object. - /// - /// - /// A new LocalUser object with the same property values as this one. - /// - public LocalUser Clone() - { - return new LocalUser(this); - } - #endregion Public Methods - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs deleted file mode 100644 index c34dbcd64d8..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace System.Management.Automation.SecurityAccountsManager.Native -{ - #region Enums - internal enum POLICY_INFORMATION_CLASS - { - PolicyAuditLogInformation = 1, - PolicyAuditEventsInformation, - PolicyPrimaryDomainInformation, - PolicyPdAccountInformation, - PolicyAccountDomainInformation, - PolicyLsaServerRoleInformation, - PolicyReplicaSourceInformation, - PolicyDefaultQuotaInformation, - PolicyModificationInformation, - PolicyAuditFullSetInformation, - PolicyAuditFullQueryInformation, - PolicyDnsDomainInformation - } - - [Flags] - internal enum LSA_AccessPolicy : long - { - POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, - POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, - POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, - POLICY_TRUST_ADMIN = 0x00000008L, - POLICY_CREATE_ACCOUNT = 0x00000010L, - POLICY_CREATE_SECRET = 0x00000020L, - POLICY_CREATE_PRIVILEGE = 0x00000040L, - POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, - POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, - POLICY_AUDIT_LOG_ADMIN = 0x00000200L, - POLICY_SERVER_ADMIN = 0x00000400L, - POLICY_LOOKUP_NAMES = 0x00000800L, - POLICY_NOTIFICATION = 0x00001000L - } - - internal enum SID_NAME_USE - { - SidTypeUser = 1, - SidTypeGroup, - SidTypeDomain, - SidTypeAlias, - SidTypeWellKnownGroup, - SidTypeDeletedAccount, - SidTypeInvalid, - SidTypeUnknown, - SidTypeComputer, - SidTypeLabel - } - - internal enum LSA_USER_ACCOUNT_TYPE - { - UnknownUserAccountType = 0, - LocalUserAccountType, - PrimaryDomainUserAccountType, - ExternalDomainUserAccountType, - LocalConnectedUserAccountType, // Microsoft Account - AADUserAccountType, - InternetUserAccountType, // Generic internet User (eg. if the SID supplied is MSA's internet SID) - MSAUserAccountType // !!! NOT YET IN THE ENUM SPECIFIED IN THE C API !!! - - } - #endregion Enums - - #region Structures - [StructLayout(LayoutKind.Sequential)] - internal struct SECURITY_DESCRIPTOR - { - public byte Revision; - public byte Sbz1; - public UInt16 Control; // SECURITY_DESCRIPTOR_CONTROL - public IntPtr Owner; - public IntPtr Group; - public IntPtr Sacl; - public IntPtr Dacl; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ACL - { - public byte AclRevision; - public byte Sbz1; - public UInt16 AclSize; - public UInt16 AceCount; - public UInt16 Sbz2; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct USER_INFO_1 - { - public string name; - public string password; - public int password_age; - public int priv; - public string home_dir; - public string comment; - public uint flags; - public string script_path; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_INFO_1008 - { - public uint flags; - } - - /// - /// The UNICODE_STRING structure is passed to a number of the SAM and LSA - /// API functions. This adds cleanup and managed-string conversion behaviors. - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct UNICODE_STRING - { - public UInt16 Length; - public UInt16 MaximumLength; - [MarshalAs(UnmanagedType.LPWStr)] - private string buffer; - - public UNICODE_STRING(string s) - { - buffer = string.IsNullOrEmpty(s) ? string.Empty : s; - Length = (UInt16)(2 * buffer.Length); - MaximumLength = Length; - } - - public override string ToString() - { - // UNICODE_STRING structures that were populated by unmanaged code - // often have buffers that point to junk if Length = 0, or that - // point to non-null-terminated strings, resulting in marshaled - // String objects that have more characters than they should. - return Length == 0 ? string.Empty - : buffer.Substring(0, Length / 2); - } - } - - [StructLayout(LayoutKind.Sequential)] - internal struct OBJECT_ATTRIBUTES : IDisposable - { - public int Length; - public IntPtr RootDirectory; - public uint Attributes; - public IntPtr SecurityDescriptor; - public IntPtr SecurityQualityOfService; - - private IntPtr objectName; - public UNICODE_STRING ObjectName; - - public void Dispose() - { - if (objectName != IntPtr.Zero) - { - Marshal.DestroyStructure(objectName); - Marshal.FreeHGlobal(objectName); - objectName = IntPtr.Zero; - } - } - } - -// These structures are filled in by Marshalling, so fields will be initialized -// invisibly to the C# compiler, and some fields will not be used in C# code. -#pragma warning disable 0649, 0169 - [StructLayout(LayoutKind.Explicit, Size = 8)] - struct LARGE_INTEGER - { - [FieldOffset(0)] - public Int64 QuadPart; - [FieldOffset(0)] - public UInt32 LowPart; - [FieldOffset(4)] - public Int32 HighPart; - } -#pragma warning restore 0649, 0169 - #endregion Structures - - internal static class Win32 - { - #region Constants - // The following are masks for the predefined standard access types - internal const UInt32 DELETE = 0x00010000; - internal const UInt32 READ_CONTROL = 0x00020000; - internal const UInt32 WRITE_DAC = 0x00040000; - internal const UInt32 WRITE_OWNER = 0x00080000; - internal const UInt32 SYNCHRONIZE = 0x00100000; - - internal const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000; - - internal const UInt32 STANDARD_RIGHTS_READ = READ_CONTROL; - internal const UInt32 STANDARD_RIGHTS_WRITE = READ_CONTROL; - internal const UInt32 STANDARD_RIGHTS_EXECUTE = READ_CONTROL; - - internal const UInt32 STANDARD_RIGHTS_ALL = 0x001F0000; - - internal const UInt32 SPECIFIC_RIGHTS_ALL = 0x0000FFFF; - - internal const UInt32 ACCESS_SYSTEM_SECURITY = 0x01000000; - - internal const UInt32 MAXIMUM_ALLOWED = 0x02000000; - - internal const UInt32 GENERIC_READ = 0x80000000; - internal const UInt32 GENERIC_WRITE = 0x40000000; - internal const UInt32 GENERIC_EXECUTE = 0x20000000; - internal const UInt32 GENERIC_ALL = 0x10000000; - - // These constants control the behavior of the FormatMessage Windows API function - internal const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; - internal const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - internal const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - internal const uint FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; - internal const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; - internal const uint FORMAT_MESSAGE_FROM_STRING = 0x00000400; - - #region Win32 Error Codes - // - // MessageText: - // - // The operation completed successfully. - // - internal const Int32 ERROR_SUCCESS = 0; - internal const Int32 NO_ERROR = ERROR_SUCCESS; - - // - // MessageId: ERROR_ACCESS_DENIED - // - // MessageText: - // - // Access is denied. - // - internal const int ERROR_ACCESS_DENIED = 5; - - // - // MessageId: ERROR_BAD_NETPATH - // - // MessageText: - // - // The network path was not found. - // - internal const int ERROR_BAD_NETPATH = 53; - - // - // MessageId: ERROR_NETWORK_ACCESS_DENIED - // - // MessageText: - // - // Network access is denied. - // - internal const int ERROR_NETWORK_ACCESS_DENIED = 65; - - // - // MessageId: ERROR_INVALID_PARAMETER - // - // MessageText: - // - // The parameter is incorrect. - // - internal const int ERROR_INVALID_PARAMETER = 87; - - // - // MessageText: - // - // The file name is too long. - // - internal const Int32 ERROR_BUFFER_OVERFLOW = 111; - - // - // MessageText: - // - // The data area passed to a system call is too small. - // - internal const Int32 ERROR_INSUFFICIENT_BUFFER = 122; - - // - // MessageId: ERROR_INVALID_LEVEL - // - // MessageText: - // - // The system call level is not correct. - // - internal const int ERROR_INVALID_LEVEL = 124; - - // - // MessageId: ERROR_INVALID_FLAGS - // - // MessageText: - // - // Invalid flags. - // - internal const Int32 ERROR_INVALID_FLAGS = 1004; - - // - // MessageId: ERROR_ILL_FORMED_PASSWORD - // - // MessageText: - // - // Unable to update the password. The value provided for the new password contains values that are not allowed in passwords. - // - internal const UInt32 ERROR_ILL_FORMED_PASSWORD = 1324; - - // - // MessageId: ERROR_PASSWORD_RESTRICTION - // - // MessageText: - // - // Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain. - // - internal const UInt32 ERROR_PASSWORD_RESTRICTION = 1325; - - // - // MessageText: - // - // No mapping between account names and security IDs was done. - // - internal const Int32 ERROR_NONE_MAPPED = 1332; - - internal const int NERR_Success = 0; - // NERR_BASE is the base of error codes from network utilities, - // chosen to avoid conflict with system and redirector error codes. - // 2100 is a value that has been assigned to us by system. - internal const int NERR_BASE = 2100; - - internal const int NERR_BadPassword = NERR_BASE + 103; // The password parameter is invalid. - internal const int NERR_UserNotFound = NERR_BASE + 121; // The user name could not be found. - internal const int NERR_NotPrimary = NERR_BASE + 126; // This operation is only allowed on the primary domain controller of the domain. - internal const int NERR_SpeGroupOp = NERR_BASE + 134; // This operation is not allowed on this special group. - internal const int NERR_PasswordTooShort = NERR_BASE + 145; // The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. - internal const int NERR_InvalidComputer = NERR_BASE + 251; // This computer name is invalid. - internal const int NERR_LastAdmin = NERR_BASE + 352; // This operation is not allowed on the last administrative account. - #endregion Win32 Error Codes - - #region SECURITY_DESCRIPTOR Control Flags - internal const UInt16 SE_DACL_PRESENT = 0x0004; - internal const UInt16 SE_SELF_RELATIVE = 0x8000; - #endregion SECURITY_DESCRIPTOR Control Flags - - #region SECURITY_INFORMATION Values - internal const int DACL_SECURITY_INFORMATION = 0x00000004; - #endregion SECURITY_INFORMATION Values - #endregion Constants - - #region Win32 Functions - [DllImport(PInvokeDllNames.LookupAccountSidDllName, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool LookupAccountSid(string systemName, - byte[] accountSid, - StringBuilder accountName, - ref Int32 nameLength, - StringBuilder domainName, - ref Int32 domainNameLength, - out SID_NAME_USE use); - - [DllImport(PInvokeDllNames.LookupAccountNameDllName, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool LookupAccountName(string systemName, - string accountName, - [MarshalAs(UnmanagedType.LPArray)] - byte[] sid, - ref uint sidLength, - StringBuilder domainName, - ref uint domainNameLength, - out SID_NAME_USE peUse); - - [DllImport(PInvokeDllNames.GetSecurityDescriptorDaclDllName, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, - [MarshalAs(UnmanagedType.Bool)] - out bool bDaclPresent, - out IntPtr pDacl, - [MarshalAs(UnmanagedType.Bool)] - out bool bDaclDefaulted); - - [DllImport(PInvokeDllNames.SetSecurityDescriptorDaclDllName, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, - [MarshalAs(UnmanagedType.Bool)] - bool bDaclPresent, - IntPtr pDacl, - [MarshalAs(UnmanagedType.Bool)] - bool bDaclDefaulted); - - [DllImport(PInvokeDllNames.FormatMessageDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern uint FormatMessage(uint dwFlags, - IntPtr lpSource, - uint dwMessageId, - uint dwLanguageId, - [Out] StringBuilder lpBuffer, - uint nSize, - string[] Arguments); - - [DllImport("ntdll.dll")] - internal static extern uint RtlNtStatusToDosError(uint ntStatus); - #endregion Win32 Functions - - #region LSA Functions - [DllImport(PInvokeDllNames.LsaOpenPolicyDllName, CharSet = CharSet.Unicode)] - internal static extern UInt32 LsaOpenPolicy(ref UNICODE_STRING SystemName, - ref OBJECT_ATTRIBUTES ObjectAttributes, - uint DesiredAccess, - out IntPtr PolicyHandle); - - [DllImport(PInvokeDllNames.LsaQueryInformationPolicyDllName, CharSet = CharSet.Unicode)] - internal static extern UInt32 LsaQueryInformationPolicy(IntPtr lsaHandle, - POLICY_INFORMATION_CLASS infoClass, - out IntPtr buffer); - - [DllImport(PInvokeDllNames.LsaFreeMemoryDllName)] - internal static extern UInt32 LsaFreeMemory(IntPtr buffer); - - [DllImport(PInvokeDllNames.LsaCloseDllName)] - internal static extern UInt32 LsaClose(IntPtr handle); - - [DllImport("api-ms-win-security-lsalookup-l1-1-2.dll")] - internal static extern UInt32 LsaLookupUserAccountType([MarshalAs(UnmanagedType.LPArray)] byte[] Sid, - out LSA_USER_ACCOUNT_TYPE accountType); - #endregion LSA Functions - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs deleted file mode 100644 index 654d221a69b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs +++ /dev/null @@ -1,519 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Diagnostics.CodeAnalysis; - -namespace System.Management.Automation.SecurityAccountsManager.Native -{ - internal static class NtStatus - { - #region Constants - // - // These values are taken from ntstatus.h - // - - // - // Severity codes - // - public const UInt32 STATUS_SEVERITY_WARNING = 0x2; - public const UInt32 STATUS_SEVERITY_SUCCESS = 0x0; - public const UInt32 STATUS_SEVERITY_INFORMATIONAL = 0x1; - public const UInt32 STATUS_SEVERITY_ERROR = 0x3; - - public const UInt32 STATUS_SUCCESS = 0x00000000; - // - // MessageText: - // - // Returned by enumeration APIs to indicate more information is available to successive calls. - // - public const UInt32 STATUS_MORE_ENTRIES = 0x00000105; - - - ///////////////////////////////////////////////////////////////////////// - // - // Standard Information values - // - ///////////////////////////////////////////////////////////////////////// - - // - // MessageText: - // - // {Object Exists} - // An attempt was made to create an object and the object name already existed. - // - public const UInt32 STATUS_OBJECT_NAME_EXISTS = 0x40000000; - - // - // MessageText: - // - // {Password Too Complex} - // The Windows password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string. - // - public const UInt32 STATUS_NULL_LM_PASSWORD = 0x4000000D; - - // - // MessageText: - // - // {Access Denied} - // A process has requested access to an object, but has not been granted those access rights. - // - public const UInt32 STATUS_ACCESS_DENIED = 0xC0000022; - - // - // MessageText: - // - // The name provided is not a properly formed account name. - // - public const UInt32 STATUS_INVALID_ACCOUNT_NAME = 0xC0000062; - - // - // MessageText: - // - // The specified account already exists. - // - public const UInt32 STATUS_USER_EXISTS = 0xC0000063; - - // - // MessageText: - // - // The specified account does not exist. - // - public const UInt32 STATUS_NO_SUCH_USER = 0xC0000064; // ntsubauth - - // - // MessageText: - // - // The specified group already exists. - // - public const UInt32 STATUS_GROUP_EXISTS = 0xC0000065; - - // - // MessageText: - // - // The specified group does not exist. - // - public const UInt32 STATUS_NO_SUCH_GROUP = 0xC0000066; - - // - // MessageText: - // - // The specified user account is already in the specified group account. Also used to indicate a group cannot be deleted because it contains a member. - // - public const UInt32 STATUS_MEMBER_IN_GROUP = 0xC0000067; - - // - // MessageText: - // - // The specified user account is not a member of the specified group account. - // - public const UInt32 STATUS_MEMBER_NOT_IN_GROUP = 0xC0000068; - - // - // MessageText: - // - // Indicates the requested operation would disable, delete or could prevent logon for an administration account. - // This is not allowed to prevent creating a situation in which the system cannot be administrated. - // - public const UInt32 STATUS_LAST_ADMIN = 0xC0000069; - - // - // MessageText: - // - // When trying to update a password, this return status indicates that the value provided as the current password is not correct. - // - public const UInt32 STATUS_WRONG_PASSWORD = 0xC000006A; // ntsubauth - - // - // MessageText: - // - // When trying to update a password, this return status indicates that the value provided for the new password contains values that are not allowed in passwords. - // - public const UInt32 STATUS_ILL_FORMED_PASSWORD = 0xC000006B; - - // - // MessageText: - // - // When trying to update a password, this status indicates that some password update rule has been violated. For example, the password may not meet length criteria. - // - public const UInt32 STATUS_PASSWORD_RESTRICTION = 0xC000006C; // ntsubauth - - // - // MessageText: - // - // The user account's password has expired. - // - public const UInt32 STATUS_PASSWORD_EXPIRED = 0xC0000071; // ntsubauth - - // - // MessageText: - // - // The referenced account is currently disabled and may not be logged on to. - // - public const UInt32 STATUS_ACCOUNT_DISABLED = 0xC0000072; // ntsubauth - - // - // MessageText: - // - // None of the information to be translated has been translated. - // - public const UInt32 STATUS_NONE_MAPPED = 0xC0000073; - - // - // MessageText: - // - // Indicates the sub-authority value is invalid for the particular use. - // - public const UInt32 STATUS_INVALID_SUB_AUTHORITY = 0xC0000076; - - // - // MessageText: - // - // Indicates the ACL structure is not valid. - // - public const UInt32 STATUS_INVALID_ACL = 0xC0000077; - - // - // MessageText: - // - // Indicates the SID structure is not valid. - // - public const UInt32 STATUS_INVALID_SID = 0xC0000078; - - // - // MessageText: - // - // Indicates the SECURITY_DESCRIPTOR structure is not valid. - // - public const UInt32 STATUS_INVALID_SECURITY_DESCR = 0xC0000079; - - // - // Network specific errors. - // - // - // - // MessageText: - // - // The request is not supported. - // - public const UInt32 STATUS_NOT_SUPPORTED = 0xC00000BB; - - // - // MessageText: - // - // This remote computer is not listening. - // - public const UInt32 STATUS_REMOTE_NOT_LISTENING = 0xC00000BC; - - // - // MessageText: - // - // Network access is denied. - // - public const UInt32 STATUS_NETWORK_ACCESS_DENIED = 0xC00000CA; - - // - // MessageText: - // - // Indicates an attempt was made to operate on the security of an object that does not have security associated with it. - // - public const UInt32 STATUS_NO_SECURITY_ON_OBJECT = 0xC00000D7; - - // - // MessageText: - // - // An internal error occurred. - // - public const UInt32 STATUS_INTERNAL_ERROR = 0xC00000E5; - - // - // MessageText: - // - // Indicates a security descriptor is not in the necessary format (absolute or self-relative). - // - public const UInt32 STATUS_BAD_DESCRIPTOR_FORMAT = 0xC00000E7; - - // - // MessageText: - // - // A specified name string is too long for its intended use. - // - public const UInt32 STATUS_NAME_TOO_LONG = 0xC0000106; - - // - // MessageText: - // - // Indicates a name specified as a remote computer name is syntactically invalid. - // - public const UInt32 STATUS_INVALID_COMPUTER_NAME = 0xC0000122; - - // - // MessageText: - // - // Indicates an operation has been attempted on a built-in (special) SAM account which is incompatible with built-in accounts. For example, built-in accounts cannot be deleted. - // - public const UInt32 STATUS_SPECIAL_ACCOUNT = 0xC0000124; - - // - // MessageText: - // - // The operation requested may not be performed on the specified group because it is a built-in special group. - // - public const UInt32 STATUS_SPECIAL_GROUP = 0xC0000125; - - // - // MessageText: - // - // The operation requested may not be performed on the specified user because it is a built-in special user. - // - public const UInt32 STATUS_SPECIAL_USER = 0xC0000126; - - // - // MessageText: - // - // Indicates a member cannot be removed from a group because the group is currently the member's primary group. - // - public const UInt32 STATUS_MEMBERS_PRIMARY_GROUP = 0xC0000127; - - // - // MessageText: - // - // The specified local group does not exist. - // - public const UInt32 STATUS_NO_SUCH_ALIAS = 0xC0000151; - - // - // MessageText: - // - // The specified account name is not a member of the group. - // - public const UInt32 STATUS_MEMBER_NOT_IN_ALIAS = 0xC0000152; - - // - // MessageText: - // - // The specified account name is already a member of the group. - // - public const UInt32 STATUS_MEMBER_IN_ALIAS = 0xC0000153; - - // - // MessageText: - // - // The specified local group already exists. - // - public const UInt32 STATUS_ALIAS_EXISTS = 0xC0000154; - - // - // MessageText: - // - // A member could not be added to or removed from the local group because the member does not exist. - // - public const UInt32 STATUS_NO_SUCH_MEMBER = 0xC000017A; - - // - // MessageText: - // - // A new member could not be added to a local group because the member has the wrong account type. - // - public const UInt32 STATUS_INVALID_MEMBER = 0xC000017B; - - // - // MessageText: - // - // The user's account has expired. - // - public const UInt32 STATUS_ACCOUNT_EXPIRED = 0xC0000193; // ntsubauth - - // - // MessageText: - // - // {Invalid ACE Condition} - // The specified access control entry (ACE) contains an invalid condition. - // - public const UInt32 STATUS_INVALID_ACE_CONDITION = 0xC00001A2; - - // - // MessageText: - // - // The user's password must be changed before signing in. - // - public const UInt32 STATUS_PASSWORD_MUST_CHANGE = 0xC0000224; // ntsubauth - - // - // MessageText: - // - // The object was not found. - // - public const UInt32 STATUS_NOT_FOUND = 0xC0000225; - - // - // MessageText: - // - // Could not find a domain controller for this domain. - // - public const UInt32 STATUS_DOMAIN_CONTROLLER_NOT_FOUND = 0xC0000233; - - // - // MessageText: - // - // The user account has been automatically locked because too many invalid logon attempts or password change attempts have been requested. - // - public const UInt32 STATUS_ACCOUNT_LOCKED_OUT = 0xC0000234; // ntsubauth - - // - // MessageText: - // - // The password provided is too short to meet the policy of your user account. Please choose a longer password. - // - public const UInt32 STATUS_PWD_TOO_SHORT = 0xC000025A; - - // - // MessageText: - // - // The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned. - // - public const UInt32 STATUS_PWD_TOO_RECENT = 0xC000025B; - - // - // MessageText: - // - // You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used. - // - public const UInt32 STATUS_PWD_HISTORY_CONFLICT = 0xC000025C; - - // - // MessageText: - // - // The password provided is too long to meet the policy of your user account. Please choose a shorter password. - // - public const UInt32 STATUS_PWD_TOO_LONG = 0xC000027A; - - // - // MessageText: - // - // Only an administrator can modify the membership list of an administrative group. - // - public const UInt32 STATUS_DS_SENSITIVE_GROUP_VIOLATION = 0xC00002CD; - - // - // MessageText: - // - // The specified group type is invalid. - // - public const UInt32 STATUS_DS_INVALID_GROUP_TYPE = 0xC00002D4; - - // - // MessageText: - // - // A local group cannot have another cross domain local group as a member. - // - public const UInt32 STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 0xC00002DB; - - // - // MessageText: - // - // Cannot change to security disabled group because of having primary members in this group. - // - public const UInt32 STATUS_DS_HAVE_PRIMARY_MEMBERS = 0xC00002DC; - - // - // MessageText: - // - // EAS policy requires that the user change their password before this operation can be performed. - // - public const UInt32 STATUS_PASSWORD_CHANGE_REQUIRED = 0xC000030C; - - #endregion Constants - - #region Public Methods - /// - /// Determine if an NTSTATUS value indicates Success. - /// - /// The NTSTATUS value returned from native functions. - /// - /// True if the NTSTATUS value indicates success, false otherwise. - /// - public static bool IsSuccess(UInt32 ntstatus) - { - return Severity(ntstatus) == STATUS_SEVERITY_SUCCESS; - } - - /// - /// Determine if an NTSTATUS value indicates an Error. - /// - /// The NTSTATUS value returned from native functions. - /// - /// True if the NTSTATUS value indicates an error, false otherwise. - /// - public static bool IsError(UInt32 ntstatus) - { - return Severity(ntstatus) == STATUS_SEVERITY_ERROR; - } - - /// - /// Determine if an NTSTATUS value indicates a Warning. - /// - /// The NTSTATUS value returned from native functions. - /// - /// True if the NTSTATUS value indicates a warning, false otherwise. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static bool IsWarning(UInt32 ntstatus) - { - return Severity(ntstatus) == STATUS_SEVERITY_WARNING; - } - - /// - /// Determine if an NTSTATUS value indicates that the value is Informational. - /// - /// The NTSTATUS value returned from native functions. - /// - /// True if the NTSTATUS value indicates that it is informational, false otherwise. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static bool IsInformational(UInt32 ntstatus) - { - return Severity(ntstatus) == STATUS_SEVERITY_INFORMATIONAL; - } - - /// - /// Return the Severity part of an NTSTATUS value. - /// - /// The NTSTATUS value returned from native functions. - /// - /// One of the STATUS_SEVERITY_* values - /// - public static uint Severity(UInt32 ntstatus) - { - return ntstatus >> 30; - } - - /// - /// Return the Facility part of an NSTATUS value. - /// - /// The NTSTATUS value returned from native functions. - /// - /// The value of the Facility portion of an NTSTATUS value. - /// - - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static uint Facility(UInt32 ntstatus) - { - return (ntstatus >> 16) & 0x0FFF; - } - - /// - /// Return the Code part of an NTSTATUS value. - /// - /// The NTSTATUS value returned from native functions. - /// - /// The value of the Code portion of an NTSTATUS value. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static uint Code(UInt32 ntstatus) - { - return ntstatus & 0xFFFF; - } - - #endregion Public Methods - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs deleted file mode 100644 index 68a7d31e833..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - /// - /// PinvokeDllNames contains the DLL names to be use for PInvoke in FullCLR/CoreCLR powershell. - /// - /// * When adding a new DLL name here, make sure that you add both the FullCLR and CoreCLR version - /// of it. Add the comment '/*COUNT*/' with the new DLL name, and make sure the 'COUNT' is the - /// same for both FullCLR and CoreCLR DLL names. - /// - internal static class PInvokeDllNames - { - internal const string GetLastErrorDllName = "api-ms-win-core-errorhandling-l1-1-0.dll"; /* 1*/ - internal const string LookupAccountSidDllName = "api-ms-win-security-lsalookup-l2-1-1.dll"; /* 2*/ - internal const string IsValidSidDllName = "api-ms-win-security-base-l1-2-0.dll"; /* 3*/ - internal const string GetLengthSidDllName = "api-ms-win-security-base-l1-2-0.dll"; /* 4*/ - internal const string LsaFreeMemoryDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 5*/ - internal const string LsaOpenPolicyDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 6*/ - internal const string LsaQueryInformationPolicyDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 7*/ - internal const string LsaCloseDllName = "api-ms-win-security-lsapolicy-l1-1-0.dll"; /* 8*/ - internal const string LookupAccountNameDllName = "api-ms-win-security-lsalookup-l2-1-1.dll"; /* 9*/ - internal const string GetComputerNameDllName = "api-ms-win-downlevel-kernel32-l2-1-0.dll"; /*10*/ - internal const string GetSecurityDescriptorDaclDllName = "api-ms-win-security-base-l1-2-0"; /*11*/ - internal const string SetSecurityDescriptorDaclDllName = "api-ms-win-security-base-l1-2-0"; /*12*/ - internal const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-1"; /*13*/ - internal const string GetVersionExDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; /*14*/ - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs deleted file mode 100644 index 3e6bbcafd10..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ /dev/null @@ -1,3275 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Security.Principal; - -using Microsoft.PowerShell.Commands; -using System.Management.Automation.SecurityAccountsManager.Extensions; -using System.Management.Automation.SecurityAccountsManager.Native; -using System.Management.Automation.SecurityAccountsManager.Native.NtSam; -using System.Text; - -using Microsoft.PowerShell.LocalAccounts; -using System.Diagnostics.CodeAnalysis; - -[module: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant")] - -namespace System.Management.Automation.SecurityAccountsManager -{ - /// - /// Defines enumeration constants for enabling and disabling something. - /// - internal enum Enabling - { - Disable = 0, - Enable - } - - /// - /// Managed version of the SAM_RID_ENUMERATION native structure, - /// to be returned from the EnumerateLocalUsers method of Sam. - /// Contains the original structure's members along with additional - /// members of use. - /// - internal class SamRidEnumeration - { -#region Original struct members - public string Name; - public UInt32 RelativeId; -#endregion Original struct members - -#region Additional members - public IntPtr domainHandle; // The domain handle used to acquire the data. -#endregion Additional members - } - - /// - /// Provides methods for manipulating local Users and Groups. - /// - internal class Sam : IDisposable - { -#region Enums - [Flags] - private enum GroupProperties - { - Name = 0x0001, // NOT changeable through Set-LocalGroup - Description = 0x0002, - - AllSetable = Description, - AllReadable = AllSetable | Name - } - - /// - /// Defines a set of flags, each corresponding to a member of LocalUser, - /// which indicate fields to be updated. - /// - /// - /// Although password can be set through Create-LocalUser and Set-LocalUser, - /// it is not a member of LocalUser so does not appear in this enumeration. - /// - [Flags] - private enum UserProperties - { - None = 0x0000, // not actually a LocalUser member - Name = 0x0001, // NOT changeable through Set-LocalUser - AccountExpires = 0x0002, - Description = 0x0004, - Enabled = 0x0008, // NOT changeable through Set-LocalUser - FullName = 0x0010, - PasswordChangeableDate = 0x0020, - PasswordExpires = 0x0040, - PasswordNeverExpires = 0x0080, - UserMayChangePassword = 0x0100, - PasswordRequired = 0x0200, - PasswordLastSet = 0x0400, // CANNOT be set by cmdlet - LastLogon = 0x0800, // CANNOT be set by cmdlet - - // All properties that can be set through Set-LocalUser - AllSetable = AccountExpires - | Description - | FullName - | PasswordChangeableDate - | PasswordExpires - | PasswordNeverExpires - | UserMayChangePassword - | PasswordRequired, - - // Properties that can be set by Create-LocalUser - AllCreateable = AllSetable | Name | Enabled, - - // Properties that can be read by e.g., Get-LocalUser - AllReadable = AllCreateable | PasswordLastSet | LastLogon - } - - private enum PasswordExpiredState - { - Unchanged = -1, - NotExpired = 0, - Expired = 1 - } - - [Flags] - internal enum ObjectAccess : uint - { - AliasRead = Win32.STANDARD_RIGHTS_READ - | ALIAS_LIST_MEMBERS, - ALiasWrite = Win32.STANDARD_RIGHTS_WRITE - | ALIAS_WRITE_ACCOUNT - | ALIAS_ADD_MEMBER - | ALIAS_REMOVE_MEMBER, - - UserAllAccess = Win32.STANDARD_RIGHTS_REQUIRED - | USER_READ_PREFERENCES - | USER_READ_LOGON - | USER_LIST_GROUPS - | USER_READ_GROUP_INFORMATION - | USER_WRITE_PREFERENCES - | USER_CHANGE_PASSWORD - | USER_FORCE_PASSWORD_CHANGE - | USER_READ_GENERAL - | USER_READ_ACCOUNT - | USER_WRITE_ACCOUNT - | USER_WRITE_GROUP_INFORMATION, - UserRead = Win32.STANDARD_RIGHTS_READ - | USER_READ_GENERAL // not in original USER_READ - | USER_READ_PREFERENCES - | USER_READ_LOGON - | USER_READ_ACCOUNT - | USER_LIST_GROUPS - | USER_READ_GROUP_INFORMATION, - UserWrite = Win32.STANDARD_RIGHTS_WRITE - | USER_WRITE_PREFERENCES - | USER_CHANGE_PASSWORD - } - - [Flags] - internal enum DomainAccess : uint - { - AllAccess = Win32.STANDARD_RIGHTS_REQUIRED - | DOMAIN_READ_OTHER_PARAMETERS - | DOMAIN_WRITE_OTHER_PARAMETERS - | DOMAIN_WRITE_PASSWORD_PARAMS - | DOMAIN_CREATE_USER - | DOMAIN_CREATE_GROUP - | DOMAIN_CREATE_ALIAS - | DOMAIN_GET_ALIAS_MEMBERSHIP - | DOMAIN_LIST_ACCOUNTS - | DOMAIN_READ_PASSWORD_PARAMETERS - | DOMAIN_LOOKUP - | DOMAIN_ADMINISTER_SERVER, - - Read = Win32.STANDARD_RIGHTS_READ - | DOMAIN_LIST_ACCOUNTS - | DOMAIN_GET_ALIAS_MEMBERSHIP - | DOMAIN_READ_OTHER_PARAMETERS, - - Write = Win32.STANDARD_RIGHTS_WRITE - | DOMAIN_WRITE_OTHER_PARAMETERS - | DOMAIN_WRITE_PASSWORD_PARAMS - | DOMAIN_CREATE_USER - | DOMAIN_CREATE_GROUP - | DOMAIN_CREATE_ALIAS - | DOMAIN_ADMINISTER_SERVER, - - Max = Win32.MAXIMUM_ALLOWED - } - - /// - /// The operation under way. Used in the class. - /// - private enum ContextOperation - { - New = 1, - Enable, - Disable, - Get, - Remove, - Rename, - Set, - AddMember, - GetMember, - RemoveMember - } - - /// - /// The type of object currently operating with. - /// used in the class. - /// - private enum ContextObjectType - { - User = 1, - Group - } -#endregion Enums - -#region Internal Classes - /// - /// Holds information about the underway operation. - /// - /// - /// Used primarily by the private ThrowOnFailure method when building - /// Exception objects to throw. - /// - private sealed class Context - { - public ContextOperation operation; - public ContextObjectType type; - public object target; - public string objectId; - public string memberId; - - /// - /// Initialize a new Context object. - /// - /// - /// One of the enumerations indicating - /// the type of operation under way. - /// - /// - /// One of the enumerations indicating - /// the type of object (user or group) being used. - /// - /// - /// A string containing the name of the object. This may be either a - /// user/group name or a string representation of a SID. - /// - /// - /// The target being operated on. - /// - /// - /// A string containing the name of the member being added or removed - /// from a group. Used only in such cases. - /// - public Context(ContextOperation operation, - ContextObjectType objectType, - string objectIdentifier, - object target, - string memberIdentifier = null) - { - this.operation = operation; - this.type = objectType; - this.objectId = objectIdentifier; - this.target = target; - this.memberId = memberIdentifier; - } - - /// - /// Default constructor. - /// - public Context() - { - } - /// - /// Gets a string containing the type of operation under way. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public string OperationName - { - get { return operation.ToString(); } - } - - /// - /// Gets a string containing the type of object ("User" or "Group") - /// being used. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public string TypeNamne - { - get { return type.ToString(); } - } - - /// - /// Gets a string containing the name of the object being used. - /// - public string ObjectName - { - get { return objectId; } - } - - /// - /// Gets a string containing the name of the member being added to - /// or removed from a group. Returns null if the operation does not - /// involve group members. - /// - public string MemberName - { - get { return memberId; } - } - } - - /// - /// Contains basic information about an Account. - /// - /// - /// AccountInfo is the return type from the private - /// LookupAccountInfo method. - /// - private sealed class AccountInfo - { - public string AccountName; - public string DomainName; - public SecurityIdentifier Sid; - public Native.SID_NAME_USE Use; - - public override string ToString() - { - if (!string.IsNullOrEmpty(DomainName)) - return DomainName + '\\' + AccountName; - else - return AccountName; - } - } -#endregion Internal Classes - -#region Constants - // - // Access rights - // - private const UInt32 ALIAS_ADD_MEMBER = 0x0001; - private const UInt32 ALIAS_REMOVE_MEMBER = 0x0002; - private const UInt32 ALIAS_LIST_MEMBERS = 0x0004; - private const UInt32 ALIAS_READ_INFORMATION = 0x0008; - private const UInt32 ALIAS_WRITE_ACCOUNT = 0x0010; - - private const UInt32 USER_READ_GENERAL = 0x0001; - private const UInt32 USER_READ_PREFERENCES = 0x0002; - private const UInt32 USER_WRITE_PREFERENCES = 0x0004; - private const UInt32 USER_READ_LOGON = 0x0008; - private const UInt32 USER_READ_ACCOUNT = 0x0010; - private const UInt32 USER_WRITE_ACCOUNT = 0x0020; - private const UInt32 USER_CHANGE_PASSWORD = 0x0040; - private const UInt32 USER_FORCE_PASSWORD_CHANGE = 0x0080; - private const UInt32 USER_LIST_GROUPS = 0x0100; - private const UInt32 USER_READ_GROUP_INFORMATION = 0x0200; - private const UInt32 USER_WRITE_GROUP_INFORMATION = 0x0400; - - private const UInt32 DOMAIN_READ_PASSWORD_PARAMETERS = 0x0001; - private const UInt32 DOMAIN_WRITE_PASSWORD_PARAMS = 0x0002; - private const UInt32 DOMAIN_READ_OTHER_PARAMETERS = 0x0004; - private const UInt32 DOMAIN_WRITE_OTHER_PARAMETERS = 0x0008; - private const UInt32 DOMAIN_CREATE_USER = 0x0010; - private const UInt32 DOMAIN_CREATE_GROUP = 0x0020; - private const UInt32 DOMAIN_CREATE_ALIAS = 0x0040; - private const UInt32 DOMAIN_GET_ALIAS_MEMBERSHIP = 0x0080; - private const UInt32 DOMAIN_LIST_ACCOUNTS = 0x0100; - private const UInt32 DOMAIN_LOOKUP = 0x0200; - private const UInt32 DOMAIN_ADMINISTER_SERVER = 0x0400; -#endregion Constants - -#region Static Data - private static SecurityIdentifier worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); -#endregion Static Data - -#region Instance Data - private IntPtr samHandle = IntPtr.Zero; - private IntPtr localDomainHandle = IntPtr.Zero; - private IntPtr builtinDomainHandle = IntPtr.Zero; - private Context context = null; - private string machineName = string.Empty; -#endregion Instance Data - -#region Construction - internal Sam() - { - OpenHandles(); - - // CoreCLR does not have Environment.MachineName, - // so we'll use this instead. - machineName = System.Net.Dns.GetHostName(); - } -#endregion Construction - -#region Public (Internal) Methods - public string StripMachineName(string name) - { - var mn = machineName + '\\'; - - if (name.StartsWith(mn, StringComparison.CurrentCultureIgnoreCase)) - return name.Substring(mn.Length); - - return name; - } -#region Local Groups - /// - /// Retrieve a named local group. - /// - /// Name of the desired local group. - /// - /// A object containing information about - /// the local group. - /// - /// - /// Thrown when the named group cannot be found. - /// - internal LocalGroup GetLocalGroup(string groupName) - { - context = new Context(ContextOperation.Get, ContextObjectType.Group, groupName, groupName); - - foreach (var sre in EnumerateGroups()) - if (sre.Name.Equals(groupName, StringComparison.CurrentCultureIgnoreCase)) - return MakeLocalGroupObject(sre); // return a populated group - - throw new GroupNotFoundException(groupName, context.target); - } - - /// - /// Retrieve a local group by SID. - /// - /// - /// A object identifying the desired group. - /// - /// - /// A object containing information about - /// the local group. - /// - /// - /// Thrown when the specified group cannot be found. - /// - internal LocalGroup GetLocalGroup(SecurityIdentifier sid) - { - context = new Context(ContextOperation.Get, ContextObjectType.Group, sid.ToString(), sid); - - foreach (var sre in EnumerateGroups()) - if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) - return MakeLocalGroupObject(sre); // return a populated group - - throw new GroupNotFoundException(sid.ToString(), context.target); - } - - /// - /// Create a local group. - /// - /// A object containing - /// information about the local group to be created. - /// - /// - /// A new LocalGroup object containing information about the newly - /// created local group. - /// - /// - /// Thrown when an attempt is made to create a local group that already - /// exists. - /// - internal LocalGroup CreateLocalGroup(LocalGroup group) - { - context = new Context(ContextOperation.New, ContextObjectType.Group, group.Name, group.Name); - - return CreateGroup(group, localDomainHandle); - } - - /// - /// Update a local group with new property values. - /// - /// - /// A object representing the group to be updated. - /// - /// - /// A LocalGroup object containing the desired changes. - /// - /// - /// Currently, a group's description is the only changeable property. - /// - internal void UpdateLocalGroup(LocalGroup group, LocalGroup changed) - { - context = new Context(ContextOperation.Set, ContextObjectType.Group, group.Name, group); - - UpdateGroup(group, changed); - } - - /// - /// Remove a local group. - /// - /// - /// A object identifying the - /// local group to be removed. - /// - /// - /// Thrown when the specified group cannot be found. - /// - internal void RemoveLocalGroup(SecurityIdentifier sid) - { - context = new Context(ContextOperation.Remove, ContextObjectType.Group, sid.ToString(), sid); - - RemoveGroup(sid); - } - - /// - /// Remove a local group. - /// - /// - /// A object containing - /// information about the local group to be removed. - /// - /// - /// Thrown when the specified group cannot be found. - /// - internal void RemoveLocalGroup(LocalGroup group) - { - context = new Context(ContextOperation.Remove, ContextObjectType.Group, group.Name, group); - - if (group.SID == null) - context.target = group = GetLocalGroup(group.Name); - - RemoveGroup(group.SID); - } - - /// - /// Rename a local group. - /// - /// - /// A object identifying - /// the local group to be renamed. - /// - /// - /// A string containing the new name for the local group. - /// - /// - /// Thrown when the specified group cannot be found. - /// - internal void RenameLocalGroup(SecurityIdentifier sid, string newName) - { - context = new Context(ContextOperation.Rename, ContextObjectType.Group, sid.ToString(), sid); - - RenameGroup(sid, newName); - } - - /// - /// Rename a local group. - /// - /// - /// A object containing - /// information about the local group to be renamed. - /// - /// - /// A string containing the new name for the local group. - /// - /// - /// Thrown when the specified group cannot be found. - /// - internal void RenameLocalGroup(LocalGroup group, string newName) - { - context = new Context(ContextOperation.Rename, ContextObjectType.Group, group.Name, group); - - if (group.SID == null) - context.target = group = GetLocalGroup(group.Name); - - RenameGroup(group.SID, newName); - } - - /// - /// Get all local groups whose names satisfy the specified predicate. - /// - /// - /// Predicate that determines whether a group satisfies the conditions. - /// - /// - /// An object containing LocalGroup - /// objects that satisfy the predicate condition. - /// - internal IEnumerable GetMatchingLocalGroups(Predicate pred) - { - context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null); - - foreach (var sre in EnumerateGroups()) - { - - if (pred(sre.Name)) - { - context.target = sre.Name; - yield return MakeLocalGroupObject(sre); - } - } - } - - /// - /// Get all local groups. - /// - /// - /// An object containing a - /// LocalGroup object for each local group. - /// - internal IEnumerable GetAllLocalGroups() - { - context = new Context(ContextOperation.Get, ContextObjectType.Group, string.Empty, null); - - foreach (var sre in EnumerateGroups()) - { - context.target = sre.Name; - yield return MakeLocalGroupObject(sre); - } - } - - /// - /// Add members to a local group. - /// - /// - /// A object identifying the group to - /// which to add members. - /// - /// - /// An object of type identifying - /// the member to be added. - /// - /// - /// An Exception object indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - internal Exception AddLocalGroupMember(LocalGroup group, LocalPrincipal member) - { - context = new Context(ContextOperation.AddMember, ContextObjectType.Group, group.Name, group); - if (group.SID == null) - context.target = group = GetLocalGroup(group.Name); - - return AddGroupMember(group.SID, member); - } - - /// - /// Add members to a local group. - /// - /// - /// A object identifying the group to - /// which to add members. - /// - /// - /// An object of type identifying - /// the member to be added. - /// - /// - /// An Exception object indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - internal Exception AddLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) - { - context = new Context(ContextOperation.AddMember, ContextObjectType.Group, groupSid.ToString(), groupSid); - - return AddGroupMember(groupSid, member); - } - - /// - /// Retrieve members of a Local group. - /// - /// - /// A object identifying the group whose members - /// are requested. - /// - /// - /// An IEnumerable of objects containing the group's - /// members. - /// - internal IEnumerable GetLocalGroupMembers(LocalGroup group) - { - context = new Context(ContextOperation.GetMember, ContextObjectType.Group, group.Name, group); - - if (group.SID == null) - context.target = group = GetLocalGroup(group.Name); - - return GetGroupMembers(group.SID); - } - - /// - /// Retrieve members of a Local group. - /// - /// - /// A object identifying the group whose members - /// are requested. - /// - /// - /// An IEnumerable of objects containing the group's - /// members. - /// - internal IEnumerable GetLocalGroupMembers(SecurityIdentifier groupSid) - { - context = new Context(ContextOperation.GetMember, ContextObjectType.Group, groupSid.ToString(), groupSid); - - return GetGroupMembers(groupSid); - } - - /// - /// Remove members from a local group. - /// - /// - /// A object identifying the group from - /// which to remove members - /// - /// - /// An object of type identifying - /// the member to be removed. - /// - /// - /// An Exception object indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - internal Exception RemoveLocalGroupMember(LocalGroup group, LocalPrincipal member) - { - context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, group.Name, group); - - if (group.SID == null) - context.target = group = GetLocalGroup(group.Name); - - return RemoveGroupMember(group.SID, member); - } - - /// - /// Remove members from a local group. - /// - /// - /// A object identifying the group from - /// which to remove members - /// - /// - /// An Object of type identifying - /// the member to be removed. - /// - /// - /// An Exception object indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - internal Exception RemoveLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) - { - context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, groupSid.ToString(), groupSid); - - return RemoveGroupMember(groupSid, member); - } -#endregion Local Groups - -#region Local Users - /// - /// Retrieve a named local user. - /// - /// Name of the desired local user. - /// - /// A object containing information about - /// the local user. - /// - /// - /// Thrown when the named user cannot be found. - /// - internal LocalUser GetLocalUser(string userName) - { - context = new Context(ContextOperation.Get, ContextObjectType.User, userName, userName); - - foreach (var sre in EnumerateUsers()) - if (sre.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase)) - return MakeLocalUserObject(sre); - - throw new UserNotFoundException(userName, userName); - } - - /// - /// Retrieve a local user by SID. - /// - /// - /// A object identifying the desired user. - /// - /// - /// A object containing information about - /// the local user. - /// - /// - /// Thrown when the specified user cannot be found. - /// - internal LocalUser GetLocalUser(SecurityIdentifier sid) - { - context = new Context(ContextOperation.Get, ContextObjectType.User, sid.ToString(), sid); - - foreach (var sre in EnumerateUsers()) - if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) - return MakeLocalUserObject(sre); // return a populated user - - throw new UserNotFoundException(sid.ToString(), sid); - } - - /// - /// Create a local user. - /// - /// A object containing - /// information about the local user to be created. - /// - /// A containing - /// the initial password to be set for the new local user. If this parameter is null, - /// no password is set. - /// - /// - /// Indicates whether PasswordNeverExpires was specified - /// - /// - /// A new LocalGroup object containing information about the newly - /// created local user. - /// - /// - /// Thrown when an attempt is made to create a local user that already - /// exists. - /// - internal LocalUser CreateLocalUser(LocalUser user, System.Security.SecureString password, bool setPasswordNeverExpires) - { - context = new Context(ContextOperation.New, ContextObjectType.User, user.Name, user); - - return CreateUser(user, password, localDomainHandle, setPasswordNeverExpires); - } - - /// - /// Remove a local user. - /// - /// - /// A object identifying - /// the local user to be removed. - /// - /// - /// Thrown when the specified user cannot be found. - /// - internal void RemoveLocalUser(SecurityIdentifier sid) - { - context = new Context(ContextOperation.Remove, ContextObjectType.User, sid.ToString(), sid); - - RemoveUser(sid); - } - - /// - /// Remove a local user. - /// - /// - /// A object containing - /// information about the local user to be removed. - /// - /// - /// Thrown when the specified user cannot be found. - /// - internal void RemoveLocalUser(LocalUser user) - { - context = new Context(ContextOperation.Remove, ContextObjectType.User, user.Name, user); - - if (user.SID == null) - context.target = user = GetLocalUser(user.Name); - - RemoveUser(user.SID); - } - - /// - /// Rename a local user. - /// - /// - /// A objects identifying - /// the local user to be renamed. - /// - /// - /// A string containing the new name for the local user. - /// - /// - /// Thrown when the specified user cannot be found. - /// - internal void RenameLocalUser(SecurityIdentifier sid, string newName) - { - context = new Context(ContextOperation.Rename, ContextObjectType.User, sid.ToString(), sid); - - RenameUser(sid, newName); - } - - /// - /// Rename a local user. - /// - /// - /// A objects containing - /// information about the local user to be renamed. - /// - /// - /// A string containing the new name for the local user. - /// - /// - /// Thrown when the specified user cannot be found. - /// - internal void RenameLocalUser(LocalUser user, string newName) - { - context = new Context(ContextOperation.Rename, ContextObjectType.User, user.Name, user); - - if (user.SID == null) - context.target = user = GetLocalUser(user.Name); - - RenameUser(user.SID, newName); - } - - /// - /// Enable or disable a Local User. - /// - /// - /// A object identifying the user to enable or disable. - /// - /// - /// One of the enumeration values, indicating whether to - /// enable or disable the user. - /// - internal void EnableLocalUser(SecurityIdentifier sid, Enabling enable) - { - context = new Context(enable == Enabling.Enable ? ContextOperation.Enable - : ContextOperation.Disable, - ContextObjectType.User, sid.ToString(), - sid); - - EnableUser(sid, enable); - } - - /// - /// Enable or disable a Local User. - /// - /// - /// A object representing the user to enable or disable. - /// - /// - /// One of the enumeration values, indicating whether to - /// enable or disable the user. - /// - internal void EnableLocalUser(LocalUser user, Enabling enable) - { - context = new Context(enable == Enabling.Enable ? ContextOperation.Enable - : ContextOperation.Disable, - ContextObjectType.User, user.Name, - user); - - if (user.SID == null) - context.target = user = GetLocalUser(user.Name); - - EnableUser(user.SID, enable); - } - - /// - /// Update a local user with new properties. - /// - /// - /// A object representing the user to be updated. - /// - /// - /// A LocalUser object containing the desired changes. - /// - /// A - /// object containing the new password. A null value in this parameter - /// indicates that the password is not to be changed. - /// - /// - /// Specifies whether the PasswordNeverExpires parameter was set. - /// - /// - /// Call this overload when intending to leave the password-expired - /// marker in its current state. To set the password and the - /// password-expired state, call the overload with a boolean as the - /// fourth parameter - /// - internal void UpdateLocalUser(LocalUser user, LocalUser changed, System.Security.SecureString password, bool? setPasswordNeverExpires) - { - context = new Context(ContextOperation.Set, ContextObjectType.User, user.Name, user); - - UpdateUser(user, changed, password, PasswordExpiredState.Unchanged, setPasswordNeverExpires); - } - - /// - /// Get all local users whose names satisfy the specified predicate. - /// - /// - /// Predicate that determines whether a user satisfies the conditions. - /// - /// - /// An object containing LocalUser - /// objects that satisfy the predicate condition. - /// - internal IEnumerable GetMatchingLocalUsers(Predicate pred) - { - context = new Context(ContextOperation.Get, ContextObjectType.User, string.Empty, null); - - foreach (var sre in EnumerateUsers()) - { - if (pred(sre.Name)) - { - context.target = sre.Name; - yield return MakeLocalUserObject(sre); - } - } - } - - /// - /// Get all local users. - /// - /// - /// An object containing a - /// LocalUser object for each local user. - /// - internal IEnumerable GetAllLocalUsers() - { - context = new Context(ContextOperation.Get, ContextObjectType.User, null, null); - - foreach (var sre in EnumerateUsers()) - yield return MakeLocalUserObject(sre); - } -#endregion Local Users - -#region Local Principals - internal LocalPrincipal LookupAccount(string name) - { - var info = LookupAccountInfo(name); - - if (info == null) - throw new PrincipalNotFoundException(name, name); - - return MakeLocalPrincipalObject(info); - } -#endregion Local Principals -#endregion Public (Internal) Methods - -#region Private Methods - /// - /// Open the handles stored by Sam instances. - /// - private void OpenHandles() - { - var systemName = new UNICODE_STRING(); - var oa = new OBJECT_ATTRIBUTES(); - IntPtr pInfo = IntPtr.Zero; - IntPtr pSid = IntPtr.Zero; - IntPtr lsaHandle = IntPtr.Zero; - UInt32 status = 0; - - try - { - status = Win32.LsaOpenPolicy(ref systemName, ref oa, (UInt32)LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION, out lsaHandle); - ThrowOnFailure(status); - - POLICY_PRIMARY_DOMAIN_INFO domainInfo; - - status = Win32.LsaQueryInformationPolicy(lsaHandle, - POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation, - out pInfo); - ThrowOnFailure(status); - status = Win32.LsaClose(lsaHandle); - ThrowOnFailure(status); - - lsaHandle = IntPtr.Zero; - - domainInfo = Marshal.PtrToStructure(pInfo); - - status = SamApi.SamConnect(ref systemName, out samHandle, SamApi.SAM_SERVER_LOOKUP_DOMAIN, ref oa); - ThrowOnFailure(status); - - // Open the local domain - status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, domainInfo.Sid, out localDomainHandle); - ThrowOnFailure(status); - - // Open the "BuiltIn" domain - SecurityIdentifier sid = new SecurityIdentifier("S-1-5-32"); - byte[] bSid = new byte[sid.BinaryLength]; - int size = Marshal.SizeOf() * bSid.Length; - - pSid = Marshal.AllocHGlobal(size); - - sid.GetBinaryForm(bSid, 0); - Marshal.Copy(bSid, 0, pSid, bSid.Length); - - status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, pSid, out builtinDomainHandle); - - ThrowOnFailure(status); - } - finally - { - if (pInfo != IntPtr.Zero) - status = Win32.LsaFreeMemory(pInfo); - - Marshal.FreeHGlobal(pSid); - - if (lsaHandle != IntPtr.Zero) - status = Win32.LsaClose(lsaHandle); - } - } - - /// - /// Find a group by SID and return a object - /// representing the group. - /// - /// A object identifying - /// the group to search for. - /// - /// A SamRidEnumeration object representing the group. - /// - /// - /// Thrown when the specified group is not found. - /// - /// - /// This method saves some time and effort over the GetGroup method - /// because it does not have to open a group to populate a full Group - /// object. - /// - private SamRidEnumeration GetGroupSre(SecurityIdentifier sid) - { - foreach (var sre in EnumerateGroups()) - if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) - return sre; - - throw new GroupNotFoundException(sid.ToString(), sid); - } - - /// - /// Find a user by SID and return a object - /// representing the user. - /// - /// A object identifying - /// the user to search for. - /// - /// A SamRidEnumeration object representing the user. - /// - /// - /// Thrown when the specified user is not found. - /// - /// - /// This method saves some time and effort over the GetUser method - /// because it does not have to open a user to populate a full LocalUser - /// object. - /// - private SamRidEnumeration GetUserSre(SecurityIdentifier sid) - { - foreach (var sre in EnumerateUsers()) - if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) - return sre; - - throw new UserNotFoundException(sid.ToString(), sid); - } - - /// - /// Enumerate local users with native SAM functions. - /// - /// Handle to the domain to enumerate over. - /// - /// An IEnumerable of SamRidEnumeration objects, one for each local user. - /// - /// - /// This is a "generator" method. Rather than returning an entire collection, - /// it uses 'yield return' to return each object in turn. - /// - private static IEnumerable EnumerateUsersInDomain(IntPtr domainHandle) - { - UInt32 status = 0; - UInt32 context = 0; - IntPtr buffer = IntPtr.Zero; - UInt32 countReturned; - - do - { - status = SamApi.SamEnumerateUsersInDomain(domainHandle, - ref context, - 0, - out buffer, - 1, - out countReturned); - - if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1) - { - if (buffer != IntPtr.Zero) - { - SAM_RID_ENUMERATION sre; - - sre = Marshal.PtrToStructure(buffer); - - SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - - yield return new SamRidEnumeration - { - Name = sre.Name.ToString(), - RelativeId = sre.RelativeId, - - domainHandle = domainHandle - }; - } - } - } while (Succeeded(status) && status != 0 && countReturned != 0); - } - - /// - /// Enumerate user objects in both the local and builtin domains. - /// - /// - /// An IEnumerable of SamRidEnumeration objects, one for each local user. - /// - /// - /// This is a "generator" method. Rather than returning an entire collection, - /// it uses 'yield return' to return each object in turn. - /// - private IEnumerable EnumerateUsers() - { - foreach (var sre in EnumerateUsersInDomain(localDomainHandle)) - yield return sre; - - foreach (var sre in EnumerateUsersInDomain(builtinDomainHandle)) - yield return sre; - } - - /// - /// Create a new user in the specified domain. - /// - /// - /// A object containing information about the new user. - /// - /// A containing - /// the initial password to be set for the new local user. If this parameter is null, - /// no password is set. - /// - /// - /// Handle to the domain in which to create the new user. - /// - /// - /// Indicates whether PasswordNeverExpires was specified - /// - /// - /// A LocalUser object that represents the newly-created user - /// - private LocalUser CreateUser(LocalUser userInfo, System.Security.SecureString password, IntPtr domainHandle, bool setPasswordNeverExpires) - { - IntPtr userHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - UNICODE_STRING str = new UNICODE_STRING(); - UInt32 status = 0; - - try - { - UInt32 relativeId = 0; - UInt32 grantedAccess = 0; - - str = new UNICODE_STRING(userInfo.Name); - - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str)); - Marshal.StructureToPtr(str, buffer, false); - - status = SamApi.SamCreateUser2InDomain(domainHandle, - ref str, - (int) SamApi.USER_NORMAL_ACCOUNT, - Win32.MAXIMUM_ALLOWED, - out userHandle, - out grantedAccess, - out relativeId); - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - buffer = IntPtr.Zero; - ThrowOnFailure(status); - - // set the various properties of the user. A SID is required because some - // operations depend on it. - userInfo.SID = RidToSid(domainHandle, relativeId); - - SetUserData(userHandle, userInfo, UserProperties.AllCreateable, password, PasswordExpiredState.NotExpired, setPasswordNeverExpires); - - return MakeLocalUserObject(new SamRidEnumeration - { - domainHandle = domainHandle, - Name = userInfo.Name, - RelativeId = relativeId - }, - userHandle); - } - catch (Exception) - { - if (IntPtr.Zero != userHandle) - { - SamApi.SamDeleteUser(userHandle); - } - - throw; - } - finally - { - if (buffer != IntPtr.Zero) - Marshal.FreeHGlobal(buffer); - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - - /// - /// Remove a group identified by SID. - /// - /// - /// A object identifying the - /// group to be removed. - /// - private void RemoveGroup(SecurityIdentifier sid) - { - var sre = GetGroupSre(sid); - - IntPtr aliasHandle = IntPtr.Zero; - UInt32 status; - try - { - status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - - status = SamApi.SamDeleteAlias(aliasHandle); - ThrowOnFailure(status); - - aliasHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteAlias succeeds - } - finally - { - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - } - - /// - /// Rename a group identified by SID. - /// - /// - /// A object identifying - /// the local group to be renamed. - /// - /// - /// A string containing the new name for the group. - /// - /// - /// Thrown when the specified group cannot be found. - /// - private void RenameGroup(SecurityIdentifier sid, string newName) - { - var sre = GetGroupSre(sid); - - IntPtr aliasHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - UInt32 status = 0; - - status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - - try - { - ALIAS_NAME_INFORMATION info = new ALIAS_NAME_INFORMATION(); - - info.Name = new UNICODE_STRING(newName); - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - - status = SamApi.SamSetInformationAlias(aliasHandle, - ALIAS_INFORMATION_CLASS.AliasNameInformation, - buffer); - ThrowOnFailure(status, - new Context { - objectId = newName, - operation = context.operation, - type = context.type - } - ); - } - finally - { - if (buffer != IntPtr.Zero) - { - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - } - - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - } - - /// - /// Add members to a group. - /// - /// - /// A object identifying the group to - /// which to add members. - /// - /// - /// An object of type identifying - /// the member to be added. - /// - /// - /// An Exception object indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - private Exception AddGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) - { - var sre = GetGroupSre(groupSid); // We'll let this throw if necessary - - IntPtr aliasHandle = IntPtr.Zero; - UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - Exception ex = null; - try - { - var sid = member.SID; - var binarySid = new byte[sid.BinaryLength]; - - sid.GetBinaryForm(binarySid, 0); - status = SamApi.SamAddMemberToAlias(aliasHandle, binarySid); - ex = MakeException(status, - new Context - { - memberId = member.ToString(), - objectId = context.objectId, - operation = context.operation, - target = context.target, - type = context.type - } - ); - - } - finally - { - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - - return ex; - } - - /// - /// Retrieve members of a group. - /// - /// - /// A object representing the group whose members - /// are requested. - /// - /// - /// An IEnumerable of objects containing the group's - /// members. - /// - private IEnumerable GetGroupMembers(SecurityIdentifier groupSid) - { - var sre = GetGroupSre(groupSid); - - IntPtr aliasHandle = IntPtr.Zero; - IntPtr memberIds = IntPtr.Zero; - UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - - try - { - UInt32 memberCount = 0; - - status = SamApi.SamGetMembersInAlias(aliasHandle, out memberIds, out memberCount); - ThrowOnFailure(status); - - if (memberCount != 0) - { - IntPtr[] idArray = new IntPtr[memberCount]; - - Marshal.Copy(memberIds, idArray, 0, (int)memberCount); - - for (int i=0; i < memberCount; i++) - { - var sid = new SecurityIdentifier(idArray[i]); - yield return MakeLocalPrincipalObject(LookupAccountInfo(sid)); - } - } - } - finally - { - if (aliasHandle != IntPtr.Zero) - SamApi.SamCloseHandle(aliasHandle); - - if (memberIds != IntPtr.Zero) - SamApi.SamFreeMemory(memberIds); - } - } - - /// - /// Remove members from a group. - /// - /// - /// A object identifying the group from - /// which to remove members - /// - /// - /// An object of type identifying - /// the member to be removed. - /// - /// - /// An IEnumerable of Exception objects indicating any errors encountered. - /// - /// - /// Thrown if the group could not be found. - /// - private Exception RemoveGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) - { - var sre = GetGroupSre(groupSid); // We'll let this throw if necessary - - IntPtr aliasHandle = IntPtr.Zero; - UInt32 status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - - // Now we're processing each member, so any further exceptions will - // be stored in the collection and returned later. - var rv = new List(); - Exception ex = null; - try - { - var sid = member.SID; - var binarySid = new byte[sid.BinaryLength]; - - sid.GetBinaryForm(binarySid, 0); - status = SamApi.SamRemoveMemberFromAlias(aliasHandle, binarySid); - - ex = MakeException(status, - new Context { - memberId = member.ToString(), - objectId = context.objectId, - operation = context.operation, - target = context.target, - type = context.type - } - ); - } - finally - { - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - - return ex; - } - - /// - /// Create a populated LocalUser object from a SamRidEnumeration object. - /// - /// - /// A object containing minimal information - /// about a local user. - /// - /// - /// A LocalUser object, populated with user information. - /// - private LocalUser MakeLocalUserObject(SamRidEnumeration sre) - { - IntPtr userHandle = IntPtr.Zero; - var status = SamApi.SamOpenUser(sre.domainHandle, - (UInt32)ObjectAccess.UserRead, - sre.RelativeId, - out userHandle); - - ThrowOnFailure(status); - - try - { - return MakeLocalUserObject(sre, userHandle); - } - finally - { - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - - /// - /// Create a populated LocalUser object from a SamRidEnumeration object, - /// using an already-opened SAM user handle. - /// - /// - /// A object containing minimal information - /// about a local user. - /// - /// - /// Handle to an open SAM user. - /// - /// - /// A LocalUser object, populated with user information. - /// - private LocalUser MakeLocalUserObject(SamRidEnumeration sre, IntPtr userHandle) - { - IntPtr buffer = IntPtr.Zero; - UInt32 status = 0; - - try - { - USER_ALL_INFORMATION allInfo; - - status = SamApi.SamQueryInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAllInformation, - out buffer); - ThrowOnFailure(status); - allInfo = Marshal.PtrToStructure(buffer); - - var userSid = RidToSid(sre.domainHandle, sre.RelativeId); - LocalUser user = new LocalUser() - { - PrincipalSource = GetPrincipalSource(sre), - SID = userSid, - - Name = allInfo.UserName.ToString(), - FullName = allInfo.FullName.ToString(), - Description = allInfo.AdminComment.ToString(), - - // TODO: why is this coming up as 864000000000 (number of ticks per day)? - PasswordChangeableDate = DateTimeFromSam(allInfo.PasswordCanChange.QuadPart), - - PasswordExpires = DateTimeFromSam(allInfo.PasswordMustChange.QuadPart), - - // TODO: why is this coming up as 0X7FFFFFFFFFFFFFFF (largest signed 64-bit, and well out of range of DateTime)? - AccountExpires = DateTimeFromSam(allInfo.AccountExpires.QuadPart), - LastLogon = DateTimeFromSam(allInfo.LastLogon.QuadPart), - PasswordLastSet = DateTimeFromSam(allInfo.PasswordLastSet.QuadPart), - - UserMayChangePassword = GetUserMayChangePassword(userHandle, userSid), - - PasswordRequired = (allInfo.UserAccountControl & SamApi.USER_PASSWORD_NOT_REQUIRED) == 0, - - Enabled = !((allInfo.UserAccountControl & SamApi.USER_ACCOUNT_DISABLED) == SamApi.USER_ACCOUNT_DISABLED) - }; - - return user; - } - finally - { - if (buffer != IntPtr.Zero) - status = SamApi.SamFreeMemory(buffer); - } - } - - /// - /// Enable or disable a user. - /// - /// - /// A object identifying the user to be - /// enabled or disabled. - /// - /// - /// One of the enumeration values indicating - /// whether the user is to be enabled or disabled. - /// - private void EnableUser(SecurityIdentifier sid, Enabling enable) - { - IntPtr userHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - UInt32 status = 0; - - var sre = GetUserSre(sid); - - status = SamApi.SamOpenUser(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out userHandle); - ThrowOnFailure(status); - - try - { - USER_ALL_INFORMATION info; - - status = SamApi.SamQueryInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAllInformation, - out buffer); - ThrowOnFailure(status); - info = Marshal.PtrToStructure(buffer); - status = SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - - UInt32 uac = info.UserAccountControl; - UInt32 enabled_state = uac & SamApi.USER_ACCOUNT_DISABLED; - - if (enable == Enabling.Enable && enabled_state == SamApi.USER_ACCOUNT_DISABLED) - uac &= ~SamApi.USER_ACCOUNT_DISABLED; - else if (enable == Enabling.Disable && enabled_state != SamApi.USER_ACCOUNT_DISABLED) - uac |= SamApi.USER_ACCOUNT_DISABLED; - else - return; - - if (uac != info.UserAccountControl) - { - info.UserAccountControl = uac; - info.WhichFields = SamApi.USER_ALL_USERACCOUNTCONTROL; - - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - status = SamApi.SamSetInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAllInformation, - buffer); - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - buffer = IntPtr.Zero; - ThrowOnFailure(status); - } - } - finally - { - if (buffer != IntPtr.Zero) - Marshal.FreeHGlobal(buffer); - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - - /// - /// Rename a user. - /// - /// - /// A object identifying the user to be - /// renamed. - /// - /// The new user name. - private void RenameUser(SecurityIdentifier sid, string newName) - { - IntPtr userHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - UInt32 status = 0; - - var sre = GetUserSre(sid); - - status = SamApi.SamOpenUser(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out userHandle); - ThrowOnFailure(status); - - try - { - USER_ACCOUNT_NAME_INFORMATION info = new USER_ACCOUNT_NAME_INFORMATION(); - - info.UserName = new UNICODE_STRING(newName); - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - - status = SamApi.SamSetInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAccountNameInformation, - buffer); - ThrowOnFailure(status, - new Context { - objectId = newName, - operation = context.operation, - type = context.type - } - ); - } - finally - { - if (buffer != IntPtr.Zero) - { - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - } - - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - - /// - /// Delete a user. - /// - /// - /// A object identifying the user to be - /// removed. - /// - private void RemoveUser(SecurityIdentifier sid) - { - IntPtr userHandle = IntPtr.Zero; - - var sre = GetUserSre(sid); - UInt32 status; - - try - { - status = SamApi.SamOpenUser(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out userHandle); - ThrowOnFailure(status); - - status = SamApi.SamDeleteUser(userHandle); - ThrowOnFailure(status); - - userHandle = IntPtr.Zero; // The handle is freed internally if SamDeleteUser succeeds - } - finally - { - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - - /// - /// Enumerate local users with native SAM functions. - /// - /// Handle to the domain to enumerate over. - /// - /// An IEnumerable of SamRidEnumeration objects, one for each local user. - /// - /// - /// This is a "generator" method. Rather than returning an entire collection, - /// it uses 'yield return' to return each object in turn. - /// - private static IEnumerable EnumerateGroupsInDomain(IntPtr domainHandle) - { - UInt32 status = 0; - UInt32 context = 0; - IntPtr buffer = IntPtr.Zero; - UInt32 countReturned; - - do - { - // Although the method name indicates that we are operating with "groups", - // it actually uses the SAM API's SamEnumerateAliasesInDomain function. - status = SamApi.SamEnumerateAliasesInDomain(domainHandle, - ref context, - out buffer, - 1, - out countReturned); - - if (status == NtStatus.STATUS_MORE_ENTRIES && countReturned == 1) - { - if (buffer != IntPtr.Zero) - { - SAM_RID_ENUMERATION sre; - - sre = Marshal.PtrToStructure(buffer); - - SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - - yield return new SamRidEnumeration - { - Name = sre.Name.ToString(), - RelativeId = sre.RelativeId, - - domainHandle = domainHandle - }; - } - } - } while (Succeeded(status) && status != 0 && countReturned != 0); - } - - /// - /// Enumerate group objects in both the local and builtin domains. - /// - /// - /// An IEnumerable of SamRidEnumeration objects, one for each local group. - /// - /// - /// This is a "generator" method. Rather than returning an entire collection, - /// it uses 'yield return' to return each object in turn. - /// - internal IEnumerable EnumerateGroups() - { - foreach (var sre in EnumerateGroupsInDomain(localDomainHandle)) - yield return sre; - - foreach (var sre in EnumerateGroupsInDomain(builtinDomainHandle)) - yield return sre; - } - - /// - /// Create a new group in the specified domain. - /// - /// - /// A object containing information about the new group. - /// - /// Handle to the domain in which to create the new group. - /// - /// A LocalGroup object that represents the newly-created group. - /// - private LocalGroup CreateGroup(LocalGroup groupInfo, IntPtr domainHandle) - { - IntPtr aliasHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - UNICODE_STRING str = new UNICODE_STRING(); - UInt32 status; - - try - { - UInt32 relativeId; - - str = new UNICODE_STRING(groupInfo.Name); - - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(str)); - Marshal.StructureToPtr(str, buffer, false); - - status = SamApi.SamCreateAliasInDomain(domainHandle, - buffer, - Win32.MAXIMUM_ALLOWED, - out aliasHandle, - out relativeId); - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - buffer = IntPtr.Zero; - ThrowOnFailure(status); - - if (!string.IsNullOrEmpty(groupInfo.Description)) - { - ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION(); - - info.AdminComment = new UNICODE_STRING(groupInfo.Description); - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - - status = SamApi.SamSetInformationAlias(aliasHandle, - ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation, - buffer); - - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - buffer = IntPtr.Zero; - ThrowOnFailure(status); - } - - return MakeLocalGroupObject(new SamRidEnumeration - { - domainHandle = domainHandle, - Name = groupInfo.Name, - RelativeId = relativeId - }, - aliasHandle); - } - finally - { - if (buffer != IntPtr.Zero) - Marshal.FreeHGlobal(buffer); - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - } - - /// - /// Update a local group with new property values. This method provides - /// the actual implementation. - /// - /// - /// A object representing the group to be updated. - /// - /// - /// A LocalGroup object containing the desired changes. - /// - /// - /// Currently, a group's description is the only changeable property. - /// - private void UpdateGroup(LocalGroup group, LocalGroup changed) - { - // Only description may be changed - if (group.Description == changed.Description) - return; - - IntPtr aliasHandle = IntPtr.Zero; - IntPtr buffer = IntPtr.Zero; - - if (group.SID == null) - group = GetLocalGroup(group.Name); - - var sre = GetGroupSre(group.SID); - UInt32 status; - - try - { - status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - ThrowOnFailure(status); - - ALIAS_ADM_COMMENT_INFORMATION info = new ALIAS_ADM_COMMENT_INFORMATION(); - - info.AdminComment = new UNICODE_STRING(changed.Description); - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - - status = SamApi.SamSetInformationAlias(aliasHandle, - ALIAS_INFORMATION_CLASS.AliasAdminCommentInformation, - buffer); - - ThrowOnFailure(status); - } - finally - { - if (buffer != IntPtr.Zero) - { - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - } - - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - } - - /// - /// Create a populated LocalGroup object from a SamRidEnumeration object. - /// - /// - /// A object containing minimal information - /// about a local group. - /// - /// - /// A LocalGroup object, populated with group information. - /// - private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre) - { - IntPtr aliasHandle = IntPtr.Zero; - var status = SamApi.SamOpenAlias(sre.domainHandle, - Win32.MAXIMUM_ALLOWED, - sre.RelativeId, - out aliasHandle); - - ThrowOnFailure(status); - - try - { - return MakeLocalGroupObject(sre, aliasHandle); - } - finally - { - if (aliasHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(aliasHandle); - } - } - - /// - /// Create a populated LocalGroup object from a SamRidEnumeration object, - /// using an already-opened SAM alias handle. - /// - /// - /// A object containing minimal information - /// about a local group. - /// - /// - /// Handle to an open SAM alias. - /// - /// - /// A LocalGroup object, populated with group information. - /// - private LocalGroup MakeLocalGroupObject(SamRidEnumeration sre, IntPtr aliasHandle) - { - IntPtr buffer = IntPtr.Zero; - UInt32 status = 0; - - try - { - ALIAS_GENERAL_INFORMATION generalInfo; - - status = SamApi.SamQueryInformationAlias(aliasHandle, - ALIAS_INFORMATION_CLASS.AliasGeneralInformation, - out buffer); - ThrowOnFailure(status); - generalInfo = Marshal.PtrToStructure(buffer); - - LocalGroup group = new LocalGroup() - { - PrincipalSource = GetPrincipalSource(sre), - SID = RidToSid(sre.domainHandle, sre.RelativeId), - - Name = generalInfo.Name.ToString(), - Description = generalInfo.AdminComment.ToString() - }; - - return group; - } - finally - { - if (buffer != IntPtr.Zero) - status = SamApi.SamFreeMemory(buffer); - } - } - - /// - /// Update a local user with new properties. - /// - /// - /// A object representing the user to be updated. - /// - /// - /// A LocalUser object containing the desired changes. - /// - /// A - /// object containing the new password. A null value in this parameter - /// indicates that the password is not to be changed. - /// - /// One of the - /// enumeration values indicating - /// whether the password-expired state is to be explicitly set or - /// left as is. - /// If the parameter is null, this parameter - /// is ignored. - /// - /// - /// Indicates whether the PasswordNeverExpires parameter was specified. - /// - private void UpdateUser(LocalUser user, - LocalUser changed, - System.Security.SecureString password, - PasswordExpiredState passwordExpired, - bool? setPasswordNeverExpires) - { - UserProperties properties = UserProperties.None; - - if (user.AccountExpires != changed.AccountExpires) - properties |= UserProperties.AccountExpires; - - if (user.Description != changed.Description) - properties |= UserProperties.Description; - - if (user.FullName != changed.FullName) - properties |= UserProperties.FullName; - - if (setPasswordNeverExpires.HasValue) - properties |= UserProperties.PasswordNeverExpires; - - if (user.UserMayChangePassword != changed.UserMayChangePassword) - properties |= UserProperties.UserMayChangePassword; - - if (user.PasswordRequired != changed.PasswordRequired) - properties |= UserProperties.PasswordRequired; - - if ( properties != UserProperties.None - || passwordExpired != PasswordExpiredState.Unchanged - || password != null) - { - IntPtr userHandle = IntPtr.Zero; - UInt32 status = 0; - - try - { - status = SamApi.SamOpenUser(localDomainHandle, - Win32.MAXIMUM_ALLOWED, - user.SID.GetRid(), - out userHandle); - ThrowOnFailure(status); - - SetUserData(userHandle, changed, properties, password, passwordExpired, setPasswordNeverExpires); - } - finally - { - if (userHandle != IntPtr.Zero) - status = SamApi.SamCloseHandle(userHandle); - } - } - } - - /// - /// Set selected properties of a user. - /// - /// Handle to an open SAM user. - /// - /// A object containing the data to set into the user. - /// - /// - /// A combination of values indicating the properties to be set. - /// - /// A - /// object containing the new password. - /// - /// One of the - /// enumeration values indicating - /// whether the password-expired state is to be explicitly set or - /// left as is. If the parameter is null, - /// this parameter is ignored. - /// - /// - /// Nullable value the specifies whether the PasswordNeverExpires bit should be flipped - /// - private void SetUserData(IntPtr userHandle, - LocalUser sourceUser, - UserProperties setFlags, - System.Security.SecureString password, - PasswordExpiredState passwordExpired, - bool? setPasswordNeverExpires) - { - IntPtr buffer = IntPtr.Zero; - - try - { - UInt32 which = 0; - UInt32 status = 0; - UInt32 uac = GetUserAccountControl(userHandle); - USER_ALL_INFORMATION info = new USER_ALL_INFORMATION(); - - if (setFlags.HasFlag(UserProperties.AccountExpires)) - { - which |= SamApi.USER_ALL_ACCOUNTEXPIRES; - info.AccountExpires.QuadPart = sourceUser.AccountExpires.HasValue - ? sourceUser.AccountExpires.Value.ToFileTime() - : 0L; - } - - if (setFlags.HasFlag(UserProperties.Description)) - { - which |= SamApi.USER_ALL_ADMINCOMMENT; - info.AdminComment = new UNICODE_STRING(sourceUser.Description); - } - - if (setFlags.HasFlag(UserProperties.Enabled)) - { - which |= SamApi.USER_ALL_USERACCOUNTCONTROL; - if (sourceUser.Enabled) - uac &= ~SamApi.USER_ACCOUNT_DISABLED; - else - uac |= SamApi.USER_ACCOUNT_DISABLED; - } - - if (setFlags.HasFlag(UserProperties.FullName)) - { - which |= SamApi.USER_ALL_FULLNAME; - info.FullName = new UNICODE_STRING(sourceUser.FullName); - } - - if (setFlags.HasFlag(UserProperties.PasswordNeverExpires)) - { - // Only modify the bit if a change was requested - if (setPasswordNeverExpires.HasValue) - { - which |= SamApi.USER_ALL_USERACCOUNTCONTROL; - if (setPasswordNeverExpires.Value) - uac |= SamApi.USER_DONT_EXPIRE_PASSWORD; - else - uac &= ~SamApi.USER_DONT_EXPIRE_PASSWORD; - } - } - - if (setFlags.HasFlag(UserProperties.PasswordRequired)) - { - which |= SamApi.USER_ALL_USERACCOUNTCONTROL; - if (sourceUser.PasswordRequired) - uac &= ~SamApi.USER_PASSWORD_NOT_REQUIRED; - else - uac |= SamApi.USER_PASSWORD_NOT_REQUIRED; - } - - if (which != 0) - { - info.WhichFields = which; - if ((which & SamApi.USER_ALL_USERACCOUNTCONTROL) != 0) - info.UserAccountControl = uac; - - buffer = Marshal.AllocHGlobal(Marshal.SizeOf()); - Marshal.StructureToPtr(info, buffer, false); - - status = SamApi.SamSetInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAllInformation, - buffer); - ThrowOnFailure(status); - status = SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - } - - if (setFlags.HasFlag(UserProperties.UserMayChangePassword)) - SetUserMayChangePassword(userHandle, sourceUser.SID, sourceUser.UserMayChangePassword); - - if (password != null) - SetUserPassword(userHandle, password, passwordExpired); - } - finally - { - if (buffer != IntPtr.Zero) - { - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - } - } - } - - /// - /// Retrieve the User's User Account Control flags. - /// - /// - /// Handle to an open user. - /// - /// - /// A 32-bit unsigned integer containing the User Account Control - /// flags as a set of bits. - /// - private UInt32 GetUserAccountControl(IntPtr userHandle) - { - IntPtr buffer = IntPtr.Zero; - USER_LOGON_INFORMATION info; - UInt32 status; - - try - { - status = SamApi.SamQueryInformationUser(userHandle, - USER_INFORMATION_CLASS.UserLogonInformation, - out buffer); - ThrowOnFailure(status); - info = Marshal.PtrToStructure(buffer); - status = SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - - return info.UserAccountControl; - } - finally - { - if (buffer != IntPtr.Zero) - status = SamApi.SamFreeMemory(buffer); - } - } - - /// - /// Retrieve the DACL from a SAM object. - /// - /// - /// A handle to the SAM object whose DACL is to be retrieved. - /// - /// - /// A object containing the DACL retrieved from - /// the SAM object. - /// - private RawAcl GetSamDacl(IntPtr objectHandle) - { - RawAcl rv = null; - IntPtr securityObject = IntPtr.Zero; - UInt32 status = 0; - - try - { - status = SamApi.SamQuerySecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, out securityObject); - ThrowOnFailure(status); - - SECURITY_DESCRIPTOR sd = Marshal.PtrToStructure(securityObject); - - bool daclPresent; - bool daclDefaulted; - IntPtr dacl; - bool ok = Win32.GetSecurityDescriptorDacl(securityObject, out daclPresent, out dacl, out daclDefaulted); - - if (!ok) - { - var error = Marshal.GetLastWin32Error(); - if (error == Win32.ERROR_ACCESS_DENIED) - throw new AccessDeniedException(context.target); - else - throw new Win32InternalException(error, context.target); - } - - if (daclPresent) - { - ACL acl = Marshal.PtrToStructure(dacl); - - if (acl.AclSize != 0) - { - // put the DACL into managed data - var bytes = new byte[acl.AclSize]; - - Marshal.Copy(dacl, bytes, 0, acl.AclSize); - rv = new RawAcl(bytes, 0); - } - } - } - finally - { - if (IntPtr.Zero != securityObject) - status = SamApi.SamFreeMemory(securityObject); - } - - return rv; - } - - /// - /// Set the DACL of a SAM object. - /// - /// - /// A handle to the SAM object whose DACL is to be retrieved. - /// - /// - /// A object containing the DACL to be set into - /// the SAM object. - /// - private void SetSamDacl(IntPtr objectHandle, RawAcl rawAcl) - { - IntPtr ipsd = IntPtr.Zero; - IntPtr ipDacl = IntPtr.Zero; - - try - { - bool present = false; - - // create a new security descriptor - var sd = new SECURITY_DESCRIPTOR() { Revision = 1 }; - ipsd = Marshal.AllocHGlobal(Marshal.SizeOf()); - - if (rawAcl != null && rawAcl.BinaryLength > 0) - { - Marshal.StructureToPtr(sd, ipsd, false); - - // put the DACL into unmanaged memory - var length = rawAcl.BinaryLength; - var bytes = new byte[length]; - rawAcl.GetBinaryForm(bytes, 0); - ipDacl = Marshal.AllocHGlobal(length); - - Marshal.Copy(bytes, 0, ipDacl, length); - present = true; - } - - // set the DACL into our new security descriptor - var ok = Win32.SetSecurityDescriptorDacl(ipsd, present, ipDacl, false); - if (!ok) - { - var error = Marshal.GetLastWin32Error(); - - if (error == Win32.ERROR_ACCESS_DENIED) - throw new AccessDeniedException(context.target); - else - throw new Win32InternalException(error, context.target); - } - - var status = SamApi.SamSetSecurityObject(objectHandle, Win32.DACL_SECURITY_INFORMATION, ipsd); - ThrowOnFailure(status); - } - finally - { - Marshal.FreeHGlobal(ipDacl); - Marshal.FreeHGlobal(ipsd); - } - } - - /// - /// Determine if a user account password may be changed by the user. - /// - /// - /// Handle to a SAM user object. - /// - /// - /// A object identifying the SAM - /// object's associated user. - /// - /// - /// True if the user account password may be changed by its user, - /// false otherwise. - /// - /// - /// The ability to for the user to change the user account password - /// is a permission in the object's DACL. This method walks through - /// the ACEs in the DACL, checking if the permission is granted to - /// either Everyone or the user identified by the userSid parameter. - /// - private bool GetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid) - { - var rawAcl = GetSamDacl(userHandle); - - // if there is no DACL, then access is granted - if (rawAcl == null) - return true; - - foreach (var a in rawAcl) - { - var ace = a as CommonAce; - if (ace != null && ace.AceType == AceType.AccessAllowed) - { - if (ace.SecurityIdentifier == worldSid || - ace.SecurityIdentifier == userSid) - { - if ((ace.AccessMask & SamApi.USER_CHANGE_PASSWORD) != 0) - return true; - } - } - } - - return false; - } - - /// - /// Set whether a user account password may be changed by the user. - /// - /// - /// Handle to a SAM user object. - /// - /// - /// A object identifying the SAM - /// object's associated user. - /// - /// - /// A boolean indicating whether the permission is to be enabled or - /// disabled. - /// - /// - /// The ability to for the user to change the user account password - /// is a permission in the object's DACL. This method walks through - /// the ACEs in the DACL, enabling or disabling the permission on ACEs - /// associated with either Everyone or the user identified by the - /// userSid parameter. - /// - private void SetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier userSid, bool enable) - { - var changed = false; - var rawAcl = GetSamDacl(userHandle); - - if (rawAcl != null) - { - foreach (var a in rawAcl) - { - var ace = a as CommonAce; - if (ace != null && ace.AceType == AceType.AccessAllowed) - { - if (ace.SecurityIdentifier == worldSid || - ace.SecurityIdentifier == userSid) - { - if (enable) - ace.AccessMask |= SamApi.USER_CHANGE_PASSWORD; - else - ace.AccessMask &= ~SamApi.USER_CHANGE_PASSWORD; - - changed = true; - } - } - } - - if (changed) - SetSamDacl(userHandle, rawAcl); - } - } - - /// - /// Determine if a user's password has expired. - /// - /// - /// Handle to an open User. - /// - /// - /// True if the user's password has expired, false otherwise. - /// - private bool IsPasswordExpired(IntPtr userHandle) - { - IntPtr buffer = IntPtr.Zero; - USER_ALL_INFORMATION info; - UInt32 status; - - try - { - status = SamApi.SamQueryInformationUser(userHandle, - USER_INFORMATION_CLASS.UserAllInformation, - out buffer); - ThrowOnFailure(status); - info = Marshal.PtrToStructure(buffer); - status = SamApi.SamFreeMemory(buffer); - buffer = IntPtr.Zero; - - return info.PasswordExpired; - } - finally - { - if (buffer != IntPtr.Zero) - status = SamApi.SamFreeMemory(buffer); - } - } - - /// - /// Set a user's password. - /// - /// Handle to an open User. - /// A - /// object containing the new password. - /// - /// One of the - /// enumeration values indicating - /// whether the password-expired state is to be explicitly set or - /// left as is. - /// - private void SetUserPassword(IntPtr userHandle, - System.Security.SecureString password, - PasswordExpiredState passwordExpired) - { - if (password != null) - { - USER_SET_PASSWORD_INFORMATION info = new USER_SET_PASSWORD_INFORMATION(); - IntPtr buffer = IntPtr.Zero; - - try - { - bool setPwExpire = false; - - switch (passwordExpired) - { - case PasswordExpiredState.Expired: - setPwExpire = true; - break; - - case PasswordExpiredState.NotExpired: - setPwExpire = false; - break; - - case PasswordExpiredState.Unchanged: - setPwExpire = IsPasswordExpired(userHandle); - break; - } - - info.Password = new UNICODE_STRING(password.AsString()); - info.PasswordExpired = setPwExpire; - - buffer = Marshal.AllocHGlobal(Marshal.SizeOf(info)); - Marshal.StructureToPtr(info, buffer, false); - - var status = SamApi.SamSetInformationUser(userHandle, - USER_INFORMATION_CLASS.UserSetPasswordInformation, - buffer); - ThrowOnFailure(status); - } - finally - { - if (buffer != IntPtr.Zero) - { - Marshal.DestroyStructure(buffer); - Marshal.FreeHGlobal(buffer); - } - } - } - } - -#region Utility Methods - /// - /// Create a - /// object from a relative ID. - /// - /// - /// Handle to the domain from which the ID was acquired. - /// - /// - /// The Relative ID value. - /// - /// - /// A SecurityIdentifier object containing the SID of the - /// object identified by the parameter. - /// - private SecurityIdentifier RidToSid(IntPtr domainHandle, uint rid) - { - IntPtr sidBytes = IntPtr.Zero; - UInt32 status = 0; - SecurityIdentifier sid = null; - - try - { - status = SamApi.SamRidToSid(domainHandle, rid, out sidBytes); - - if (status == NtStatus.STATUS_NOT_FOUND) - throw new InternalException(status, - StringUtil.Format(Strings.RidToSidFailed, rid), - ErrorCategory.ObjectNotFound); - ThrowOnFailure(status); - - sid = new SecurityIdentifier(sidBytes); - } - finally - { - if (IntPtr.Zero != sidBytes) - status = SamApi.SamFreeMemory(sidBytes); - } - - return sid; - } - - /// - /// Lookup the account identified by the specified SID. - /// - /// - /// A object identifying the account - /// to look up. - /// - /// - /// A object contains information about the - /// account, or null if no matching account was found. - /// - private AccountInfo LookupAccountInfo(SecurityIdentifier sid) - { - var sbAccountName = new StringBuilder(); - var sbDomainName = new StringBuilder(); - var accountNameLength = sbAccountName.Capacity; - var domainNameLength = sbDomainName.Capacity; - SID_NAME_USE use; - var error = Win32.NO_ERROR; - var bytes = new byte[sid.BinaryLength]; - - sid.GetBinaryForm(bytes, 0); - - if (!Win32.LookupAccountSid(null, - bytes, - sbAccountName, ref accountNameLength, - sbDomainName, ref domainNameLength, - out use)) - { - error = Marshal.GetLastWin32Error(); - - if (error == Win32.ERROR_INSUFFICIENT_BUFFER) - { - sbAccountName.EnsureCapacity(accountNameLength); - sbDomainName.EnsureCapacity((int)domainNameLength); - error = Win32.NO_ERROR; - if (!Win32.LookupAccountSid(null, - bytes, - sbAccountName, ref accountNameLength, - sbDomainName, ref domainNameLength, - out use)) - error = Marshal.GetLastWin32Error(); - } - } - - if (error == Win32.ERROR_SUCCESS) - return new AccountInfo - { - AccountName = sbAccountName.ToString(), - DomainName = sbDomainName.ToString(), - Sid = sid, - Use = use - }; - else if (error == Win32.ERROR_NONE_MAPPED) - return null; - else - throw new Win32InternalException(error, context.target); - } - - /// - /// Lookup the account identified by specified account name. - /// - /// - /// A string containing the name of the account to look up. - /// - /// - /// A object contains information about the - /// account, or null if no matching account was found. - /// - private AccountInfo LookupAccountInfo(string accountName) - { - var sbDomainName = new StringBuilder(); - var domainNameLength = (uint)sbDomainName.Capacity; - byte [] sid = null; - uint sidLength = 0; - SID_NAME_USE use; - int error = Win32.NO_ERROR; - - if (!Win32.LookupAccountName(null, - accountName, - sid, - ref sidLength, - sbDomainName, - ref domainNameLength, - out use)) - { - error = Marshal.GetLastWin32Error(); - if (error == Win32.ERROR_INSUFFICIENT_BUFFER || error == Win32.ERROR_INVALID_FLAGS) - { - sid = new byte[sidLength]; - sbDomainName.EnsureCapacity((int)domainNameLength); - error = Win32.NO_ERROR; - - if (!Win32.LookupAccountName(null, - accountName, - sid, - ref sidLength, - sbDomainName, - ref domainNameLength, - out use)) - error = Marshal.GetLastWin32Error(); - } - - } - - if (error == Win32.ERROR_SUCCESS) - { - // Bug: 7407413 : - // If accountname is in the format domain1\user1, - // then AccountName.ToString() will return domain1\domain1\user1 - // Ideally , accountname should be processed to hold only account name (without domain) - // as we are keeping the domain in 'DomainName' variable. - - int index = accountName.IndexOf("\\", StringComparison.CurrentCultureIgnoreCase); - if (index > -1) - { - accountName = accountName.Substring(index + 1); - } - - return new AccountInfo - { - AccountName = accountName, - DomainName = sbDomainName.ToString(), - Sid = new SecurityIdentifier(sid, 0), - Use = use - }; - } - else if (error == Win32.ERROR_NONE_MAPPED) - return null; - else if (error == Win32.ERROR_ACCESS_DENIED) - throw new AccessDeniedException(context.target); - else - throw new Win32InternalException(error, context.target); - } - - /// - /// Create a object from information in - /// an AccountInfo object. - /// - /// - /// An AccountInfo object containing information about the account - /// for which the LocalPrincipal object is being created. This parameter - /// may be null, in which case this method returns null. - /// - /// - /// A new LocalPrincipal object representing the account, or null if the - /// parameter is null. - /// - private LocalPrincipal MakeLocalPrincipalObject(AccountInfo info) - { - if (info == null) - return null; // this is a legitimate case - - var rv = new LocalPrincipal(info.ToString()); - rv.SID = info.Sid; - rv.PrincipalSource = GetPrincipalSource(info); - - switch (info.Use) - { - case SID_NAME_USE.SidTypeAlias: // TODO: is this the right thing to do??? - case SID_NAME_USE.SidTypeGroup: - case SID_NAME_USE.SidTypeWellKnownGroup: - rv.ObjectClass = Strings.ObjectClassGroup; - break; - - case SID_NAME_USE.SidTypeUser: - rv.ObjectClass = Strings.ObjectClassUser; - break; - - default: - rv.ObjectClass = Strings.ObjectClassOther; - break; - } - - return rv; - } - - /// - /// Indicate whether a Status code is a successful value. - /// - /// - /// One of the NTSTATUS code values indicating the error, if any. - /// - /// - /// True if the Status code represents a success, false otherwise. - /// - private static bool Succeeded(UInt32 ntStatus) - { - return NtStatus.IsSuccess(ntStatus); - } - - /// - /// Helper to throw an exception if the provided Status code - /// represents a failure. - /// - /// - /// One of the NTSTATUS code values indicating the error, if any. - /// - /// - /// A object containing information about the - /// current operation. If this parameter is null, the class's context - /// is used. - /// - private void ThrowOnFailure(UInt32 ntStatus, Context context = null) - { - if (NtStatus.IsError(ntStatus)) - { - var ex = MakeException(ntStatus, context); - - if (ex != null) - throw ex; - } - } - - /// - /// Create an appropriate exception from the specified status code. - /// - /// - /// One of the NTSTATUS code values indicating the error, if any. - /// - /// - /// A object containing information about the - /// current operation. If this parameter is null, the class's context - /// is used. - /// - /// - /// An object, or an object derived from Exception, - /// appropriate to the error. If does not - /// indicate an error, the method returns null. - /// - private Exception MakeException(UInt32 ntStatus, Context context = null) - { - if (!NtStatus.IsError(ntStatus)) - return null; - - if (context == null) - context = this.context; - - switch (ntStatus) - { - case NtStatus.STATUS_ACCESS_DENIED: - return new AccessDeniedException(context.target); - - case NtStatus.STATUS_INVALID_ACCOUNT_NAME: - return new InvalidNameException(context.ObjectName, context.target); - - case NtStatus.STATUS_USER_EXISTS: - if (context.operation == ContextOperation.New && - context.type == ContextObjectType.User) - { - return new UserExistsException(context.ObjectName, context.target); - } - else - { - return new NameInUseException(context.ObjectName, context.target); - } - - case NtStatus.STATUS_ALIAS_EXISTS: - if (context.operation == ContextOperation.New && - context.type == ContextObjectType.Group) - { - return new GroupExistsException(context.ObjectName, context.target); - } - else - { - return new NameInUseException(context.ObjectName, context.target); - } - - case NtStatus.STATUS_GROUP_EXISTS: - return new NameInUseException(context.ObjectName, context.target); - - case NtStatus.STATUS_NO_SUCH_ALIAS: - case NtStatus.STATUS_NO_SUCH_GROUP: - return new GroupNotFoundException(context.ObjectName, context.target); - - case NtStatus.STATUS_NO_SUCH_USER: - return new UserNotFoundException(context.ObjectName, context.target); - - case NtStatus.STATUS_SPECIAL_GROUP: // The group specified is a special group and cannot be operated on in the requested fashion. - // case NtStatus.STATUS_SPECIAL_ALIAS: // referred to in source for SAM api, but not in ntstatus.h!!! - - return new InvalidOperationException(StringUtil.Format(Strings.InvalidForGroup, context.ObjectName)); - - case NtStatus.STATUS_SPECIAL_USER: // The user specified is a special user and cannot be operated on in the requested fashion. - return new InvalidOperationException(StringUtil.Format(Strings.InvalidForUser, context.ObjectName)); - - case NtStatus.STATUS_NO_SUCH_MEMBER: - return new MemberNotFoundException(context.MemberName, context.ObjectName); - - case NtStatus.STATUS_MEMBER_IN_ALIAS: - case NtStatus.STATUS_MEMBER_IN_GROUP: - if (context.operation == ContextOperation.Remove && - context.type == ContextObjectType.Group) - { - return new InvalidOperationException(StringUtil.Format(Strings.GroupHasMembers, context.ObjectName)); - } - else - { - return new MemberExistsException(context.MemberName, context.ObjectName, context.target); - } - - case NtStatus.STATUS_MEMBER_NOT_IN_ALIAS: - case NtStatus.STATUS_MEMBER_NOT_IN_GROUP: - return new MemberNotFoundException(context.MemberName, context.ObjectName); - - case NtStatus.STATUS_MEMBERS_PRIMARY_GROUP: - return new InvalidOperationException(StringUtil.Format(Strings.MembersPrimaryGroup, context.ObjectName)); - - case NtStatus.STATUS_LAST_ADMIN: // Cannot delete the last administrator. - return new InvalidOperationException(Strings.LastAdmin); - - case NtStatus.STATUS_ILL_FORMED_PASSWORD: - case NtStatus.STATUS_PASSWORD_RESTRICTION: - return new InvalidPasswordException(Native.Win32.RtlNtStatusToDosError(ntStatus)); - - // TODO: do we want to handle these? - // they appear to be returned only in functions we are not calling - case NtStatus.STATUS_INVALID_SID: // member sid is corrupted - case NtStatus.STATUS_INVALID_MEMBER: // member has wrong account type - default: - return new InternalException(ntStatus, context.target); - } - } - - /// - /// Create a DateTime object from a 64-bit value from one of the SAM - /// structures. - /// - /// - /// A signed 64-bit value representing a date and time. - /// - /// - /// A nullable DateTime object representing a date and time, - /// or null if the parameter is zero. - /// - private static DateTime? DateTimeFromSam(Int64 samValue) - { - if (samValue == 0 || samValue == 0X7FFFFFFFFFFFFFFF) - return null; - - return DateTime.FromFileTime(samValue); - } - - /// - /// Determine the source of a user or group. Either local, Active Directory, - /// or Azure AD. - /// - /// - /// A object identifying the user or group. - /// - /// - /// One of the enumerations identifying the - /// source of the object. - /// - private PrincipalSource? GetPrincipalSource(SecurityIdentifier sid) - { - var bSid = new byte[sid.BinaryLength]; - - sid.GetBinaryForm(bSid, 0); - - var type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType; - - // Use LsaLookupUserAccountType for Windows 10 and later. - // Earlier versions of the OS will leave the property NULL because - // it is too error prone to attempt to replicate the decisions of - // LsaLookupUserAccountType. - var os = GetOperatingSystem(); - if (os.Version.Major >= 10) - { - UInt32 status = Native.Win32.LsaLookupUserAccountType(bSid, out type); - if (NtStatus.IsError(status)) - type = LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType; - - switch (type) - { - case LSA_USER_ACCOUNT_TYPE.ExternalDomainUserAccountType: - case LSA_USER_ACCOUNT_TYPE.PrimaryDomainUserAccountType: - return PrincipalSource.ActiveDirectory; - - case LSA_USER_ACCOUNT_TYPE.LocalUserAccountType: - return PrincipalSource.Local; - - case LSA_USER_ACCOUNT_TYPE.AADUserAccountType: - return PrincipalSource.AzureAD; - - // Currently, there is no value returned by LsaLookupUserAccountType - // that corresponds to LSA_USER_ACCOUNT_TYPE.MSAUserAccountType, - // but there may be in the future, so we'll account for it here. - case LSA_USER_ACCOUNT_TYPE.MSAUserAccountType: - case LSA_USER_ACCOUNT_TYPE.LocalConnectedUserAccountType: - return PrincipalSource.MicrosoftAccount; - - case LSA_USER_ACCOUNT_TYPE.InternetUserAccountType: - return sid.IsMsaAccount() - ? PrincipalSource.MicrosoftAccount - : PrincipalSource.Unknown; - - case LSA_USER_ACCOUNT_TYPE.UnknownUserAccountType: - default: - return PrincipalSource.Unknown; - } - } - else - { - return null; - } - } - - /// - /// Determine the source of a user or group. Either local, Active Directory, - /// or Azure AD. - /// - /// - /// An object containing information about the - /// user or group. - /// - /// - /// One of the enumerations identifying the - /// source of the object. - /// - private PrincipalSource? GetPrincipalSource(AccountInfo info) - { - return GetPrincipalSource(info.Sid); - } - - /// - /// Determine the source of a user or group. Either local, Active Directory, - /// or Azure AD. - /// - /// - /// A object identifying the user or group. - /// - /// - /// One of the enumerations identifying the - /// source of the object. - /// - private PrincipalSource? GetPrincipalSource(SamRidEnumeration sre) - { - return GetPrincipalSource(RidToSid(sre.domainHandle, sre.RelativeId)); - } - -#if CORECLR - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct OSVERSIONINFOEX - { - // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) - public int OSVersionInfoSize; - public int MajorVersion; - public int MinorVersion; - public int BuildNumber; - public int PlatformId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string CSDVersion; - public ushort ServicePackMajor; - public ushort ServicePackMinor; - public short SuiteMask; - public byte ProductType; - public byte Reserved; - } - - [DllImport(PInvokeDllNames.GetVersionExDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx); - - private static volatile OperatingSystem localOs; - - /// - /// It only contains the properties that get used in powershell. - /// - internal sealed class OperatingSystem - { - private Version _version; - private string _servicePack; - private string _versionString; - - internal OperatingSystem(Version version, string servicePack) - { - ArgumentNullException.ThrowIfNull(version); - - _version = version; - _servicePack = servicePack; - } - - /// - /// OS version. - /// - public Version Version - { - get { return _version; } - } - - /// - /// VersionString. - /// - public string VersionString - { - get - { - if (_versionString != null) - { - return _versionString; - } - - // It's always 'VER_PLATFORM_WIN32_NT' for NanoServer and IoT - const string os = "Microsoft Windows NT "; - if (string.IsNullOrEmpty(_servicePack)) - { - _versionString = os + _version.ToString(); - } - else - { - _versionString = os + _version.ToString(3) + " " + _servicePack; - } - - return _versionString; - } - } - } -#endif - - // Wraps calls to acquire the OperatingSystem version - private OperatingSystem GetOperatingSystem() - { -#if CORECLR - if (localOs == null) - { - OSVERSIONINFOEX osviex = new OSVERSIONINFOEX(); - osviex.OSVersionInfoSize = Marshal.SizeOf(osviex); - if (!GetVersionEx(ref osviex)) - { - int errorCode = Marshal.GetLastWin32Error(); - throw new Win32Exception(errorCode); - } - - Version ver = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor); - localOs = new OperatingSystem(ver, osviex.CSDVersion); - } - - return localOs; -#else - return Environment.OSVersion; -#endif - } -#endregion Utility Methods -#endregion Private Methods - -#region IDisposable Support - private bool disposedValue = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - { - UInt32 status = 0; - - if (disposing) - { - // no managed objects need disposing. - } - - if (builtinDomainHandle != IntPtr.Zero) - { - status = SamApi.SamCloseHandle(builtinDomainHandle); - builtinDomainHandle = IntPtr.Zero; - } - - if (localDomainHandle != IntPtr.Zero) - { - status = SamApi.SamCloseHandle(localDomainHandle); - localDomainHandle = IntPtr.Zero; - } - - if (samHandle != IntPtr.Zero) - { - status = SamApi.SamCloseHandle(samHandle); - samHandle = IntPtr.Zero; - } - - if (NtStatus.IsError(status)) - { - // Do nothing to satisfy CA1806: Do not ignore method results. We want the dispose to proceed regardless of the handle close status. - } - - disposedValue = true; - } - } - - // override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. - ~Sam() - { - // Do not change this code. Put cleanup code in Dispose(bool disposing) above. - Dispose(false); - } - - // This code added to correctly implement the disposable pattern. - public void Dispose() - { - // Do not change this code. Put cleanup code in Dispose(bool disposing) above. - Dispose(true); - // uncomment the following line if the finalizer is overridden above. - GC.SuppressFinalize(this); - } -#endregion IDisposable Support - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs deleted file mode 100644 index c2d9bc7f95b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -//using System.Management.Automation.SecurityAccountsManager.Native; - -namespace System.Management.Automation.SecurityAccountsManager.Native.NtSam -{ - #region Enums - internal enum ALIAS_INFORMATION_CLASS - { - AliasGeneralInformation = 1, - AliasNameInformation, - AliasAdminCommentInformation, - AliasReplicationInformation, - AliasExtendedInformation, - } - - internal enum GROUP_INFORMATION_CLASS - { - GroupGeneralInformation = 1, - GroupNameInformation, - GroupAttributeInformation, - GroupAdminCommentInformation, - GroupReplicationInformation - } - - internal enum USER_INFORMATION_CLASS - { - UserGeneralInformation = 1, - UserPreferencesInformation, - UserLogonInformation, - UserLogonHoursInformation, - UserAccountInformation, - UserNameInformation, - UserAccountNameInformation, - UserFullNameInformation, - UserPrimaryGroupInformation, - UserHomeInformation, - UserScriptInformation, - UserProfileInformation, - UserAdminCommentInformation, - UserWorkStationsInformation, - UserSetPasswordInformation, - UserControlInformation, - UserExpiresInformation, - UserInternal1Information, - UserInternal2Information, - UserParametersInformation, - UserAllInformation, - UserInternal3Information, - UserInternal4Information, - UserInternal5Information, - UserInternal4InformationNew, - UserInternal5InformationNew, - UserInternal6Information, - UserExtendedInformation, - UserLogonUIInformation, - } - - #endregion Enums - - #region Structures - [StructLayout(LayoutKind.Sequential)] - internal struct SR_SECURITY_DESCRIPTOR - { - public UInt32 Length; - public IntPtr SecurityDescriptor; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct LOGON_HOURS - { - public UInt16 UnitsPerWeek; - - // - // UnitsPerWeek is the number of equal length time units the week is - // divided into. This value is used to compute the length of the bit - // string in logon_hours. Must be less than or equal to - // SAM_UNITS_PER_WEEK (10080) for this release. - // - // LogonHours is a bit map of valid logon times. Each bit represents - // a unique division in a week. The largest bit map supported is 1260 - // bytes (10080 bits), which represents minutes per week. In this case - // the first bit (bit 0, byte 0) is Sunday, 00:00:00 - 00-00:59; bit 1, - // byte 0 is Sunday, 00:01:00 - 00:01:59, etc. A NULL pointer means - // DONT_CHANGE for SamSetInformationUser() calls. - // - - public IntPtr LogonHours; - } - - [StructLayout(LayoutKind.Sequential, Pack=4)] - internal struct USER_ALL_INFORMATION - { - public LARGE_INTEGER LastLogon; - public LARGE_INTEGER LastLogoff; - public LARGE_INTEGER PasswordLastSet; - public LARGE_INTEGER AccountExpires; - public LARGE_INTEGER PasswordCanChange; - public LARGE_INTEGER PasswordMustChange; - public UNICODE_STRING UserName; - public UNICODE_STRING FullName; - public UNICODE_STRING HomeDirectory; - public UNICODE_STRING HomeDirectoryDrive; - public UNICODE_STRING ScriptPath; - public UNICODE_STRING ProfilePath; - public UNICODE_STRING AdminComment; - public UNICODE_STRING WorkStations; - public UNICODE_STRING UserComment; - public UNICODE_STRING Parameters; - public UNICODE_STRING LmPassword; - public UNICODE_STRING NtPassword; - public UNICODE_STRING PrivateData; - public SR_SECURITY_DESCRIPTOR SecurityDescriptor; - public UInt32 UserId; - public UInt32 PrimaryGroupId; - public UInt32 UserAccountControl; - public UInt32 WhichFields; - public LOGON_HOURS LogonHours; - public UInt16 BadPasswordCount; - public UInt16 LogonCount; - public UInt16 CountryCode; - public UInt16 CodePage; - [MarshalAs(UnmanagedType.I1)] - public bool LmPasswordPresent; - [MarshalAs(UnmanagedType.I1)] - public bool NtPasswordPresent; - [MarshalAs(UnmanagedType.I1)] - public bool PasswordExpired; - [MarshalAs(UnmanagedType.I1)] - public bool PrivateDataSensitive; - } - - [StructLayout(LayoutKind.Sequential, Pack=4)] - internal struct USER_GENERAL_INFORMATION - { - public UNICODE_STRING UserName; - public UNICODE_STRING FullName; - public UInt32 PrimaryGroupId; - public UNICODE_STRING AdminComment; - public UNICODE_STRING UserComment; - } - - [StructLayout(LayoutKind.Sequential, Pack=4)] - internal struct USER_LOGON_INFORMATION - { - public UNICODE_STRING UserName; - public UNICODE_STRING FullName; - public UInt32 UserId; - public UInt32 PrimaryGroupId; - public UNICODE_STRING HomeDirectory; - public UNICODE_STRING HomeDirectoryDrive; - public UNICODE_STRING ScriptPath; - public UNICODE_STRING ProfilePath; - public UNICODE_STRING WorkStations; - public LARGE_INTEGER LastLogon; - public LARGE_INTEGER LastLogoff; - public LARGE_INTEGER PasswordLastSet; - public LARGE_INTEGER PasswordCanChange; - public LARGE_INTEGER PasswordMustChange; - public LOGON_HOURS LogonHours; - public UInt16 BadPasswordCount; - public UInt16 LogonCount; - public UInt32 UserAccountControl; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_ACCOUNT_NAME_INFORMATION - { - public UNICODE_STRING UserName; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_FULL_NAME_INFORMATION - { - public UNICODE_STRING FullName; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_NAME_INFORMATION - { - public UNICODE_STRING UserName; - public UNICODE_STRING FullName; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_ADMIN_COMMENT_INFORMATION - { - UNICODE_STRING AdminComment; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_EXPIRES_INFORMATION - { - // LARGE_INTEGER AccountExpires; - public Int64 AccountExpires; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_SET_PASSWORD_INFORMATION - { - public UNICODE_STRING Password; - public bool PasswordExpired; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct USER_LOGON_HOURS_INFORMATION - { - public LOGON_HOURS LogonHours; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct POLICY_PRIMARY_DOMAIN_INFO - { - public UNICODE_STRING Name; - public IntPtr Sid; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ALIAS_GENERAL_INFORMATION - { - public UNICODE_STRING Name; - public UInt32 MemberCount; - public UNICODE_STRING AdminComment; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ALIAS_NAME_INFORMATION - { - public UNICODE_STRING Name; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct ALIAS_ADM_COMMENT_INFORMATION - { - public UNICODE_STRING AdminComment; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SAMPR_GROUP_GENERAL_INFORMATION - { - public UNICODE_STRING Name; - public UInt32 Attributes; - public UInt32 MemberCount; - public UNICODE_STRING AdminComment; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SAMPR_GROUP_NAME_INFORMATION - { - public UNICODE_STRING Name; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SAM_RID_ENUMERATION - { - public UInt32 RelativeId; - public UNICODE_STRING Name; - } - #endregion Structures - - /// - /// Provides methods for invoking functions in the Windows - /// Security Accounts Manager (SAM) API. - /// - internal static class SamApi - { - #region Constants - // Account enumeration filters, may be combined by bitwise OR - internal const UInt32 SAM_USER_ENUMERATION_FILTER_LOCAL = 0x00000001; - internal const UInt32 SAM_USER_ENUMERATION_FILTER_INTERNET = 0x00000002; - internal const UInt32 SAM_SERVER_LOOKUP_DOMAIN = 0x0020; - - // - // Bits to be used in UserAllInformation's WhichFields field (to indicate - // which items were queried or set). - // - internal const UInt32 USER_ALL_USERNAME = 0x00000001; - internal const UInt32 USER_ALL_FULLNAME = 0x00000002; - internal const UInt32 USER_ALL_USERID = 0x00000004; - internal const UInt32 USER_ALL_PRIMARYGROUPID = 0x00000008; - internal const UInt32 USER_ALL_ADMINCOMMENT = 0x00000010; - internal const UInt32 USER_ALL_USERCOMMENT = 0x00000020; - internal const UInt32 USER_ALL_HOMEDIRECTORY = 0x00000040; - internal const UInt32 USER_ALL_HOMEDIRECTORYDRIVE = 0x00000080; - internal const UInt32 USER_ALL_SCRIPTPATH = 0x00000100; - internal const UInt32 USER_ALL_PROFILEPATH = 0x00000200; - internal const UInt32 USER_ALL_WORKSTATIONS = 0x00000400; - internal const UInt32 USER_ALL_LASTLOGON = 0x00000800; - internal const UInt32 USER_ALL_LASTLOGOFF = 0x00001000; - internal const UInt32 USER_ALL_LOGONHOURS = 0x00002000; - internal const UInt32 USER_ALL_BADPASSWORDCOUNT = 0x00004000; - internal const UInt32 USER_ALL_LOGONCOUNT = 0x00008000; - internal const UInt32 USER_ALL_PASSWORDCANCHANGE = 0x00010000; - internal const UInt32 USER_ALL_PASSWORDMUSTCHANGE = 0x00020000; - internal const UInt32 USER_ALL_PASSWORDLASTSET = 0x00040000; - internal const UInt32 USER_ALL_ACCOUNTEXPIRES = 0x00080000; - internal const UInt32 USER_ALL_USERACCOUNTCONTROL = 0x00100000; - internal const UInt32 USER_ALL_PARAMETERS = 0x00200000; // ntsubauth - internal const UInt32 USER_ALL_COUNTRYCODE = 0x00400000; - internal const UInt32 USER_ALL_CODEPAGE = 0x00800000; - internal const UInt32 USER_ALL_NTPASSWORDPRESENT = 0x01000000; // field AND boolean - internal const UInt32 USER_ALL_LMPASSWORDPRESENT = 0x02000000; // field AND boolean - internal const UInt32 USER_ALL_PRIVATEDATA = 0x04000000; // field AND boolean - internal const UInt32 USER_ALL_PASSWORDEXPIRED = 0x08000000; - internal const UInt32 USER_ALL_SECURITYDESCRIPTOR = 0x10000000; - internal const UInt32 USER_ALL_OWFPASSWORD = 0x20000000; // boolean - - internal const UInt32 USER_ALL_UNDEFINED_MASK = 0xC0000000; - - // - // Bit masks for the UserAccountControl member of the USER_ALL_INFORMATION structure - // - internal const UInt32 USER_ACCOUNT_DISABLED = 0x00000001; - internal const UInt32 USER_HOME_DIRECTORY_REQUIRED = 0x00000002; - internal const UInt32 USER_PASSWORD_NOT_REQUIRED = 0x00000004; - internal const UInt32 USER_TEMP_DUPLICATE_ACCOUNT = 0x00000008; - internal const UInt32 USER_NORMAL_ACCOUNT = 0x00000010; - internal const UInt32 USER_MNS_LOGON_ACCOUNT = 0x00000020; - internal const UInt32 USER_INTERDOMAIN_TRUST_ACCOUNT = 0x00000040; - internal const UInt32 USER_WORKSTATION_TRUST_ACCOUNT = 0x00000080; - internal const UInt32 USER_SERVER_TRUST_ACCOUNT = 0x00000100; - internal const UInt32 USER_DONT_EXPIRE_PASSWORD = 0x00000200; - internal const UInt32 USER_ACCOUNT_AUTO_LOCKED = 0x00000400; - internal const UInt32 USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000800; - internal const UInt32 USER_SMARTCARD_REQUIRED = 0x00001000; - internal const UInt32 USER_TRUSTED_FOR_DELEGATION = 0x00002000; - internal const UInt32 USER_NOT_DELEGATED = 0x00004000; - internal const UInt32 USER_USE_DES_KEY_ONLY = 0x00008000; - internal const UInt32 USER_DONT_REQUIRE_PREAUTH = 0x00010000; - internal const UInt32 USER_PASSWORD_EXPIRED = 0x00020000; - internal const UInt32 USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x00040000; - internal const UInt32 USER_NO_AUTH_DATA_REQUIRED = 0x00080000; - internal const UInt32 USER_PARTIAL_SECRETS_ACCOUNT = 0x00100000; - internal const UInt32 USER_USE_AES_KEYS = 0x00200000; - - // - // Access rights for user object - // - internal const UInt16 USER_CHANGE_PASSWORD = 0x0040; - #endregion Constants - - #region Sam Functions - [DllImport("samlib.dll")] - public static extern UInt32 SamConnect(ref UNICODE_STRING serverName, - out IntPtr serverHandle, - UInt32 desiredAccess, - ref OBJECT_ATTRIBUTES objectAttributes); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamRidToSid(IntPtr objectHandle, UInt32 rid, out IntPtr sid); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamCloseHandle(IntPtr serverHandle); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamFreeMemory(IntPtr buffer); - - #region Domain Functions - [DllImport("samlib.dll")] - internal static extern UInt32 SamOpenDomain(IntPtr serverHandle, - UInt32 desiredAccess, - IntPtr domainId, - out IntPtr domainHandle); - #endregion Domain Functions - - #region Alias Functions - [DllImport("samlib.dll")] - internal static extern UInt32 SamEnumerateAliasesInDomain(IntPtr domainHandle, - ref UInt32 enumerationContext, - out IntPtr buffer, - UInt32 preferredMaximumLength, - out UInt32 countReturned); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamCreateAliasInDomain(IntPtr domainHandle, - IntPtr accountName, // PUNICODE_STRING - UInt32 desiredAccess, - out IntPtr aliasHandle, - out UInt32 relativeId); // PULONG - - [DllImport("samlib.dll")] - internal static extern UInt32 SamOpenAlias(IntPtr domainHandle, - UInt32 desiredAccess, - UInt32 aliasId, - out IntPtr aliasHandle); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamQueryInformationAlias(IntPtr aliasHandle, - ALIAS_INFORMATION_CLASS aliasInformationClass, - out IntPtr buffer); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamSetInformationAlias(IntPtr aliasHandle, - ALIAS_INFORMATION_CLASS aliasInformationClass, - IntPtr buffer); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamDeleteAlias(IntPtr aliasHandle); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamAddMemberToAlias(IntPtr aliasHandle, - byte[] memberId); // PSID - - [DllImport("samlib.dll")] - internal static extern UInt32 SamRemoveMemberFromAlias(IntPtr aliasHandle, - byte[] memberId); // PSID - - [DllImport("samlib.dll")] - internal static extern UInt32 SamGetMembersInAlias(IntPtr aliasHandle, - out IntPtr memberIds, // PSID ** - out UInt32 memberCount); - #endregion Alias Functions - - #region User Functions - [DllImport("samlib.dll")] - internal static extern UInt32 SamOpenUser(IntPtr domainHandle, - UInt32 desiredAccess, - UInt32 userID, - out IntPtr userHandle); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamDeleteUser(IntPtr aliasHandle); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamEnumerateUsersInDomain(IntPtr domainHandle, - ref UInt32 enumerationContext, - UInt32 userAccountControl, - out IntPtr buffer, - UInt32 preferredMaximumLength, - out UInt32 countReturned); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamCreateUser2InDomain(IntPtr domainHandle, - ref UNICODE_STRING accountName, - Int32 accountType, - UInt32 desiredAccess, - out IntPtr userHandle, - out UInt32 grantedAccess, - out UInt32 relativeId); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamQueryInformationUser(IntPtr userHandle, - USER_INFORMATION_CLASS userInformationClass, - out IntPtr buffer); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamSetInformationUser(IntPtr userHandle, - USER_INFORMATION_CLASS userInformationClass, - IntPtr buffer); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamQuerySecurityObject(IntPtr objectHandle, - UInt32 securityInformation, - out IntPtr securityDescriptor); - - [DllImport("samlib.dll")] - internal static extern UInt32 SamSetSecurityObject(IntPtr objectHandle, - UInt32 SecurityInformation, - IntPtr SecurityDescriptor); - #endregion User Functions - #endregion Sam Functions - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs deleted file mode 100644 index 25bbeb49329..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Globalization; -using System.Management.Automation.SecurityAccountsManager.Native; - -namespace System.Management.Automation.SecurityAccountsManager -{ - /// - /// Contains utility functions for formatting localizable strings. - /// - internal class StringUtil - { - /// - /// Private constructor to present auto-generation of a default constructor with greater accessibility. - /// - private StringUtil() - { - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal static string Format(string str) - { - return string.Format(CultureInfo.CurrentCulture, str); - } - - internal static string Format(string fmt, string p0) - { - return string.Format(CultureInfo.CurrentCulture, fmt, p0); - } - - internal static string Format(string fmt, string p0, string p1) - { - return string.Format(CultureInfo.CurrentCulture, fmt, p0, p1); - } - - internal static string Format(string fmt, uint p0) - { - return string.Format(CultureInfo.CurrentCulture, fmt, p0); - } - - internal static string Format(string fmt, int p0) - { - return string.Format(CultureInfo.CurrentCulture, fmt, p0); - } - - internal static string FormatMessage(uint messageId, string[] args) - { - var message = new System.Text.StringBuilder(256); - UInt32 flags = Win32.FORMAT_MESSAGE_FROM_SYSTEM; - - if (args == null) - flags |= Win32.FORMAT_MESSAGE_IGNORE_INSERTS; - else - flags |= Win32.FORMAT_MESSAGE_ARGUMENT_ARRAY; - - var length = Win32.FormatMessage(flags, IntPtr.Zero, messageId, 0, message, 256, args); - - if (length > 0) - return message.ToString(); - - return null; - } - - internal static string GetSystemMessage(uint messageId) - { - return FormatMessage(messageId, null); - } - } -} diff --git a/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj b/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj deleted file mode 100644 index a85b06d4f90..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - PowerShell's Microsoft.PowerShell.LocalAccounts project - Microsoft.PowerShell.LocalAccounts - - - - - - - diff --git a/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx b/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx deleted file mode 100644 index ff1c4a17427..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Access denied. - - - Account {0} was not found. - - - Add member {0} - - - Disable local user - - - Enable local user - - - Create new local group - - - Create new local user - - - Remove local group - - - Remove member {0} - - - Remove local user - - - Rename local group to {0} - - - Rename local user to {0} - - - Modify local group - - - Modify local user - - - Group {0} already exists. - - - The group {0} still has members. - - - Group {0} was not found. - - - The operation is not allowed for group {0}. - - - The operation is not allowed for user {0}. - - - The name {0} is invalid. - - - Parameter {0} and parameter {1} may not be used together. - - - Invalid password. - - - Cannot remove the last Administrator - - - {0} is already a member of group {1}. - - - Member {0} was not found in group {1}. - - - User {0} may not be removed from its primary group. - - - The name {0} is already in use. - - - Group - - - Other - - - User - - - The password cannot be set because a password restriction is in place. - - - Principal {0} was not found. - - - RID {0} was not found. - - - An unspecified error occurred. - - - An unspecified error occurred: status = {0} - - - An unspecified error occurred: error code = {0} - - - User {0} already exists. - - - User {0} was not found. - -